2011-07-22 14 views
0

我想從我的計算機到2D圖形中加載圖像,這樣我以後可以對其進行編輯,然後我想將它添加到JPanel。如果您需要查看我的項目,我可以將其發送給您。的Java:從文件,編輯原圖並添加到JPanel的

void loadImage() 
{ 

    FileDialog fd = new FileDialog(new Frame(), "Please choose a file:", FileDialog.LOAD); 
    fd.show(); 
    if (fd.getFile() != null) 
    { 
     File fil = new File(fd.getDirectory(), fd.getFile()); 
     strDirectory = fd.getDirectory(); 
     strFileType = fd.getFile(); 
     mainImage.setIcon(new ImageIcon(fil.toString())); 
     getFileList(strDirectory); 
     checkFileType(strFileType); 
    } 
} 

在此先感謝

+0

究竟是什麼,你想達到什麼目的? – Moonbeam

+0

你的問題是什麼? –

回答

2

要將圖像加載到內存中,你可以使用ImageIO.read(File)。隨後編輯它,通過調用createGraphics()取得它的Graphics2D實例:

BufferedImage img = ImageIO.read(yourFile); 
Graphics2D g = img.createGraphics(); 
// Draw here on the graphics 
g.dispose(); 

您可以通過設置RenderingHint繪製前甚至打開抗鋸齒:

g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
        RenderingHints.VALUE_ANTIALIASING_ON); 

然後,將其添加到一個JPanel,創建自定義的JComponent和組件的一個實例添加到您的JPanel:

+0

+1擴展JComponent的 – mKorbel

1

對於你應該使用圖像加載對象與方法read(File file)see docs。然後你會得到BufferedImage實例,它的您可以通過Graphics2D實例,該實例,您將通過對圖像實例see docs調用createGraphics()獲得進行更改。最後一件事,重寫方法paintComponent()JPanel或更好JComponentsee docs在那裏你可以在Graphics實例繪製你的形象,你會通過調用drawImage(Image img, int x, int y, ImageObserver observer)see docs其中ImageObserver設置爲null得到的參數paintComponent(Graphics g)方法。

+3

不覆蓋'漆(...)',而不是覆蓋'的paintComponent(...)'。 – Moonbeam

+0

對,我的錯,謝謝.. – Sorceror

2

請仔細閱讀本教程大約Icon in Swing和圖像/ ImageIcon的將被放置到JLabel,這種方式消除了所有的煩惱,從油漆/ paintComponents來到...

+0

+1不擴展*任何*組件。 –