How do I add a background image to a Jframe?

0

I'm trying to change the background image of my JFrame, but I'm having difficulties. Here is the code:

public class teste_tamagotchi extends JFrame {

private JPanel contentPane;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                final Image backgroundImage = javax.imageio.ImageIO.read(new File("C:\Bibliotecas\Imagens\galaxy-wallpaper-11.jpg"));
                setContentPane(new JPanel(new BorderLayout()) {
                    @Override public void paintComponent(Graphics g) {
                        g.drawImage(backgroundImage, 0, 0, null);
                    }
                });
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

And I have the following error:

  

Can not make a static reference to the non-static method   setContentPane (Container) from the type JFrame

    
asked by anonymous 14.10.2016 / 17:14

1 answer

3

You can not reference a non-static method within a static.

In the case of code, setContentPane() can not be called inside the main method because it belongs to an instance of JFrame .

Create a constructor or method that constructs your JFrame within the class, and inside main just instantiate your window:

public class teste_tamagotchi extends JFrame {

private JPanel contentPane;
/**
 * Launch the application.
 */

public teste_tamagotchi(){

    try {
        final Image backgroundImage = javax.imageio.ImageIO.read(new File("C:\Bibliotecas\Imagens\galaxy-wallpaper-11.jpg"));
        setContentPane(new JPanel(new BorderLayout()) {
            @Override public void paintComponent(Graphics g) {
                g.drawImage(backgroundImage, 0, 0, null);
            }
        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
           teste_tamagotchi t = new teste_tamagotchi();
           t.setVisible(true);
        }
    });
}

Another tip is to avoid using lower case-initiated names as class names, there is a convention for this, indicating that you should always initialize the name of a class by following the CamelCase .

    
14.10.2016 / 17:29