How do I add a background image to a Jframe?

Asked

Viewed 933 times

1

I’m trying to change the background image of my Jframe, but I’m having a hard time. Here’s 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 mistake:

Cannot make a Static Reference to the non-static method setContentPane(Container) from the type Jframe

  • 1

    Can add a [mcve] of your jframe?

  • I’ll edit my code, all right ?

1 answer

3

You cannot reference a non-static method within a static.

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

Create a constructor or method to build your own JFrame within the class, and within the main just instate 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 names started with lowercase letter as class names, there is a convention for this indicating that you should always start with uppercase the name of a class, following pattern Camelcase.

  • @Paul’s answer answered him?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.