2012-06-26 66 views
2

我需要一些關於Java Swing組件及其功能的幫助。我需要將一個JPanel添加到JFrame並在其上繪製Ellipse2D。到Ellipse2D我想添加另一個元素,在我的情況下它是一張圖片(現在我使用ImageIcon,也許是錯誤的)。如何在面板上添加Ellipse2D和圖片,如附圖所示?如何在JPanel上添加多個圖層

我需要分離圖像的原因是,因爲我有時需要更改橢圓的填充顏色。

感謝您的任何幫助。 enter image description here

回答

5

您需要的是創建自定義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()方法更改後的顏色。

+0

還需要設置任何的首選大小或覆蓋的位置'的getPreferredSize()',使得組件佈局正確 –

+0

你會如何繪製圖像? 'Graphics2D'提供'drawImage()'方法,這對我來說看起來有點複雜,因爲有一些Observer可以設置。 – nyyrikki

+0

只是將觀察者設置爲空:http://stackoverflow.com/questions/1684422/how-does-java-graphics-drawimage-work-and-what-is-the-role-of-imageobserver – lbalazscs

0

採取兩個圖像作爲圖像的圖標,如

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); 
相關問題