2016-04-17 61 views
1

如何設置JComponent的背景?我現在有這個類:JAVA Paint組件的背景

import java.awt.BorderLayout; 
import java.awt.Graphics; 
import java.awt.Image; 

import javax.swing.JComponent; 

public class ImagePanel extends JComponent { 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 
    private Image image; 
    public ImagePanel(Image image) { 
     this.setLayout(new BorderLayout()); 
     this.image = image; 
    } 

    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawImage(image, 0, 0, this); 
    } 
} 


private BufferedImage myImage; 
private JButton button = new JButton("Click"); 
try { 
     myImage = ImageIO.read(new File("/images/picture.png")); 

    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

我用下面的代碼繪製的JFrame的內容窗格中,但我不知道該怎麼做了一個JButton

回答

2

對顯示圖像的最佳方式一個JButton是通過setIcon(myIcon)

private BufferedImage myImage; 
private JButton button = new JButton("Click"); 

public MyClass() { 
    try { 
     // much better to get the image as a resource 
     // NOT as a File 
     myImage = ImageIO.read(new File("/images/picture.png")); 
     Icon buttonIcon = new ImageIcon(myImage); 
     button.setIcon(buttonIcon); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

幽州上的按鈕創建一個ImageIcon,然後設置JButton的圖標:

這不會將其設置爲背景。它只是建立在文本旁邊的圖標

這時你有幾種選擇:

  • 擴展JButton,並以類似於你如何與JComponent中做其的paintComponent方法來繪製圖像。理解這會改變按鈕邊框的繪製,並且它可能無法像你想要的那樣工作,但對你來說測試很容易。
  • 或者從圖像中獲取圖形對象,將文本繪製到圖像上,然後創建一個ImageIcon並將其放在按鈕上。
+0

這不會將其設置爲背景。它只是在文本旁邊創建一個圖標 – Ben

+0

@Ben:請參閱編輯以回答。 –

+0

如果我使用我的方式,通過讓類擴展JButton,按鈕上的文本將不會顯示出來 – Ben