简体   繁体   中英

How to paint a JFrame at creation?

I'm trying to paint a background image onto a JFrame for a life simulation game I'm making. This is my code:

public class MainFrame extends JFrame  {
 //creates image variables
Image background;

 public MainFrame(int w, int h) {
    //creates new JFrame and sets some other properties
    super("Life Simulation");
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(new Dimension(w,h));
    //creates images
    background = Toolkit.getDefaultToolkit().createImage("img/default.jpg");
    this.repaint();
    setVisible(true);
}
 @Override
 public void paint(Graphics g) {
         super.paint(g);
         Graphics2D g2d = (Graphics2D) g;
         g.drawImage(background,0,0,null);
     }
}

I've tried to repaint it before setting it visible, but nothing. When I launch my program from my main method, the JFrame is simply blank. However, if I resize it in the slightest, the paint method is called and the background image is painted.

This is my main method:

public class Main {

public static void main(String[] args) {
    MainFrame frame = new MainFrame(1080,720);
    frame.repaint(); //tried invoking paint() here as well but again to no avail
}

}

EDIT: I believe it is also worth mentioning that I have little to no experience beforehand with using paint() or any of its variants, only knowledge of how it SHOULD be implemented and its abilities.

Oh, I'd like to stress the importance of providing an appropriate ImageObserver object when calling the drawImage method. Instead of passing null , I'd recommend passing this :

g.drawImage(background, 0, 0, this);

You can read about the importance of specifying an ImageObserver when loading images asynchronously via Toolkit.createImage .

Aside: Though paintComponent isn't defined for JFrame, I would recommend avoiding overriding JFrame's paint method. Instead, you could create either a reusable ImagePanel class, or just use an anonymous class, and then use that to set the content pane of your JFrame.

Here's an example of an ImagePanel class:

class ImagePanel extends JPanel {
    private Image image;

    public ImagePanel(Image image) {
        this.image = image;
    }

    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

Or if you prefer an anonymous class:

setContentPane(new JPanel() {
    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM