2016-04-17 3 views
1

JComponentの背景を設定するにはどうすればよいですか?私は現在、このクラスをしている:上の画像を表示するための最良の方法を私はJFrameののコンテンツペインをペイントするには、次のコードを使用JAVAペイントコンポーネントの背景

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(); 
    } 

、しかし、私は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(); 
    } 
} 

あなたの状態を経由してのJButtonのアイコンをボタンでイメージアイコンを作成して設定することです:

これはバックグラウンドとして設定されていません。

  • のJButtonを拡張し、あなたはJComponentにそれをやっているのと同じようにそのpaintComponentメソッドでイメージを描く:それはちょうど

は、その後、あなたがいくつかのオプションがあり、次のテキストにアイコンを作成します。ボタンの枠線などの描画が変更され、望むように動作しない場合がありますが、テストするのは簡単です。

  • 画像からGraphicsオブジェクトを取得し、画像にテキストを描画します。次にからImageIconを作成し、ボタンに配置します。
  • +0

    これはバックグラウンドとして設定されていません。それはテキストの隣にアイコンを作成するだけです。 – Ben

    +0

    @Ben:答えを編集するをご覧ください。 –

    +0

    私の方法を使用する場合、クラスをJButtonに拡張すると、ボタン上のテキストが – Ben