JFrame appears blank when components are loading images outside the paintComponent(); method

半城伤御伤魂 提交于 2019-12-08 09:02:03

问题


Now this might sound very strange, which is also the reason I think it's a bug in Java itself.

I'm currently making custom components for my applications. These components (which extent JComponent) overwrite the paintComponent(); method. For some reason the frame appeared blank when any of these componenets was used as soon as I implemented images in the components, I did some debuggin and I found out the following: As soon as the code inside this overwritten method draws an image which was stored in a variable outside of the method itself, like a non-static class variable, the frame will appear blank when shown, until it's being resized. Everything works fine when using images stored in a variable in the paintComponent(); method itself. What happends here, and how am I able to solve this issue? I really need to use images stored in class variable to cache these images, otherwise it would be very performance intensive to load every image again and again.

Code similar to the folowing example works fine;

public class MyComponent extends JComponent {

    @Override
    public void paintComponenet(Graphics g) {
        Image img = ImageIO.read(getClass().getResource("/res/myImg.png"));
        g.drawImage(img, 0, 0, null);
    }
}

The frame appears blank when something like this is used;

public class MyComponent extends JComponent {

    private Image img = ImageIO.read(getClass().getResource("/res/myImg.png"));

    @Override
    public void paintComponenet(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}

Loading the image (in the above example) inside the constructor or any other method won't have effect.

NOTE: The frame the components are used in isn't packed before (or after) it's being shown. This shouldn't make any sense though, because it works fine when using variables inside the paintComponent(); method itself.


回答1:


Answer by @trashgod


Be sure that Swing GUI objects are constructed and manipulated only on the event dispatch thread‌​.

For example, use the following code to initialize your frame that shows blank, this should solve your problem;

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        new MyFrame();
    }
});


来源:https://stackoverflow.com/questions/20037617/jframe-appears-blank-when-components-are-loading-images-outside-the-paintcompone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!