Ben
Ben

Reputation: 95

JAVA Paint component's background

How can i set the background of JComponent ? I currently have this class :

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

I used the following code to paint the JFrame's content pane, but i don't know how to do it for a JButton

Upvotes: 1

Views: 231

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

The best way to display an image on a JButton is to create an ImageIcon with the button and then set the JButton's icon via 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();
    } 
}

You state:

This doesn't set it as background. It just create an icon next to the text

Then you have several options:

  • Extend JButton and draw the image in its paintComponent method similar to how you're doing it with JComponent. Understand though that this will change the drawing of the button's borders and such and it may not work like you'd want, but it's easy for you to test.
  • Or get the Graphics object from the image, draw in your text onto the image, then create an ImageIcon out of it and place it on your button.

Upvotes: 2

Related Questions