0

What is the best way to add a background image to a JPanel/JLabel when a JButton is called? I know how to get the JButton action and such. I just can't figure out or find a way to get the background image to change when that button is pressed.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    For better help sooner, post an [SSCCE](http://sscce.org/). That might answer questions that result from things like *"I just can't figure out or find a way to get the background image to change when that button is pressed."* E.G. How do you load it in the first place? – Andrew Thompson Jun 14 '12 at 04:39

2 Answers2

6

Here is an example:

enter image description here

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class ModifiableBackgroundFrame extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 1L;
    private ImageIcon image;
    private JPanel pan;
    private JButton btn;
    private int count = 0;
    private static final String[] images = 
        {"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg",
        "http://www.psdgraphics.com/wp-content/uploads/2009/02/abstract-background.jpg",
        "http://hdwallpaperpics.com/wallpaper/picture/image/background.jpg",
        "http://www.highresolutionpics.info/wp-content/uploads/images/beautiful-on-green-backgrounds-for-powerpoint.jpg"};

    public ModifiableBackgroundFrame()
    {
        super("The title");

        image = new ImageIcon();

        btn = new JButton("Change background");
        btn.setFocusPainted(false);
        btn.addActionListener(this);
        pan = new JPanel()
        {
            private static final long serialVersionUID = 1L;

            @Override
            public void paintComponent(Graphics g)
            {
                g.drawImage(image.getImage(), 0, 0, null);
            }
        };
        pan.setPreferredSize(new Dimension(400, 400));

        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(pan, BorderLayout.CENTER);
        contentPane.add(btn, BorderLayout.SOUTH);

        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new ModifiableBackgroundFrame();
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        btn.setEnabled(false);
        btn.setText("Loading...");
        new SwingWorker<Image, Void>()
        {
            @Override
            protected Image doInBackground() throws Exception
            {
                return ImageIO.read(new URL(images[count++ % 4]));
            }

            @Override
            protected void done()
            {
                try
                {
                    image.setImage(get());
                    pan.repaint();
                }
                catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
                catch(ExecutionException e)
                {
                    e.printStackTrace();
                }
                btn.setText("Change background");
                btn.setEnabled(true);
            }
        }.execute();
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
2

In your JButton's actionPerformed, you can call JLabel.setIcon(Icon) to set a background image.

final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        label.setIcon(new ImageIcon(SOME_IMAGE));
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • That does not seem to work right.. Still is not changing the label on the button. I am not sure why. –  Jun 14 '12 at 06:22