Search code examples
javaswingjbutton

How to Add a url Image to a JButton


edit enter image description here

enter image description here

I use the code below to add a background image to a JPanel, problem is I can't figure out a way to add an image to a JButton.. any ideas?

    public void displayGUI() {
    JFrame frame = new JFrame("Painting Example");


    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(440, 385);
    JPanel panel = new JPanel();
    frame.add(panel);

    JButton button = new JButton("want picture here");
    panel.add(button);


    button.addActionListener(new Action7());
}

class Custom4 extends JPanel {

    public BufferedImage image;

    public Custom4() {
        try {

            image = ImageIO.read(new URL("http://i68.tinypic.com/2itmno6.jpg"));

        } catch (IOException ioe) {
            System.out.println("Unable to fetch image.");
            ioe.printStackTrace();
        }
    }

    public Dimension getPreferredSize() {
        return (new Dimension(image.getWidth(), image.getHeight()));
    }

    public void paintComponent(Graphics x) {
        super.paintComponent(x);
        x.drawImage(image, 0, 0, this);
    }
}

Solution

  • Just use the JButton Icon constructor, and pass it an ImageIcon.

    E.g. instead of

    JButton button = new JButton("want picture here");
    

    do

    JButton button = new JButton(new ImageIcon(new URL("http://i68.tinypic.com/2itmno6.jpg")));
    

    Since the URL constructor throws a MalformedURLException, you'll also need to wrap this in a try-catch block (and put your button use statements in there as well). To scale it, you also need some extra calls. Additionally, you can remove the visible parts of the button completely, by removing border and content. Since you have a JPanel behind the button, you'll need to set that to be transparent as well. The full code is below:

    try {
        JButton button = new JButton(new ImageIcon(((new ImageIcon(
            new URL("http://i68.tinypic.com/2itmno6.jpg"))
            .getImage()
            .getScaledInstance(64, 64, java.awt.Image.SCALE_SMOOTH)))));
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setContentAreaFilled(false);
        panel.setOpaque(false);
        panel.add(button);
    
        button.addActionListener(new Action7());
    } 
    catch (MalformedURLException e) {
        // exception handler code here
        // ...
    }
    

    64x64 are the image dimensions here, simply change them to the desired dimensions for your image.