我需要一些關於Java Swing組件及其功能的幫助。我需要將一個JPanel
添加到JFrame
並在其上繪製Ellipse2D
。到Ellipse2D
我想添加另一個元素,在我的情況下它是一張圖片(現在我使用ImageIcon
,也許是錯誤的)。如何在面板上添加Ellipse2D
和圖片,如附圖所示?如何在JPanel上添加多個圖層
我需要分離圖像的原因是,因爲我有時需要更改橢圓的填充顏色。
感謝您的任何幫助。
我需要一些關於Java Swing組件及其功能的幫助。我需要將一個JPanel
添加到JFrame
並在其上繪製Ellipse2D
。到Ellipse2D
我想添加另一個元素,在我的情況下它是一張圖片(現在我使用ImageIcon
,也許是錯誤的)。如何在面板上添加Ellipse2D
和圖片,如附圖所示?如何在JPanel上添加多個圖層
我需要分離圖像的原因是,因爲我有時需要更改橢圓的填充顏色。
感謝您的任何幫助。
您需要的是創建自定義JPanel
實現並覆蓋paintComponent
方法。
它裏面,你只是做:
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw ellipse here
// Draw your image here. It will be drawn on top of the ellipse.
}
這種方式,你可以按住橢圓填充顏色在CustomPanel
類,並調用repaint()
方法更改後的顏色。
你的想法,可以很好的說明(包括代碼示例)在神諭教程How to Decorate Components with the JLayer Class
通知JLayer
僅供Java7可用,但它的基礎上(爲的Java6)JXLayer
您也可以使用(我正在使用)GlassPane
,使用與Swing GUI相同/相似的輸出
EDIT
相當容易和漂亮的輸出是通過使用OverlayLayout,有可能疊加J/Component
(S)與Graphics
例如a few examples
採取兩個圖像作爲圖像的圖標,如
ImageIcon car=new ImageIcon("image path");
ImageIcon elipse=new ImageIcon("image path");
添加這兩個圖標圖標兩個標籤
JLabel carLabel=new JLabel(car);
JLabel ellipseLabel=new JLabel(ellipse);
和設置橢圓和汽車
carLabel.setBounds(0,0,50,50);
ellipseLabel.setBounds(10,10,50,50);
還需要設置任何的首選大小或覆蓋的位置'的getPreferredSize()',使得組件佈局正確 –
你會如何繪製圖像? 'Graphics2D'提供'drawImage()'方法,這對我來說看起來有點複雜,因爲有一些Observer可以設置。 – nyyrikki
只是將觀察者設置爲空:http://stackoverflow.com/questions/1684422/how-does-java-graphics-drawimage-work-and-what-is-the-role-of-imageobserver – lbalazscs