Images in paintComponent only show up after resizing the window

若如初见. 提交于 2019-11-27 02:16:33

You need to call frame.pack() to do the initial layout. Resizing the window automatically causes the layout to be fixed, but frame.setSize(...) does not*.

Move frame.setVisible(true) to the end of your run method (i.e. after you've constructed all the UI elements) and put frame.pack() just before frame.setVisible(true). (Thanks Hovercraft and MadProgrammer for pointing this out)

*At least, it doesn't if the frame is not visible. It might work if the frame is already visible; try it and see.

EDIT: Now that I re-read the javadoc, you probably don't want pack after all - it will resize the frame for you. Without testing it, I guess that moving setVisible to the end will work; if it doesn't then use revalidate rather than pack to get the layout engine to run.

EDIT 2: Now that I re-re-read the javadoc, setVisible will validate the window if it is not already displayable. So you won't need an explicit call to revalidate. setSize will invalidate the component but will not revalidate it.

TL;DR: It's worth reading up on how validation and displayability work in Swing so you don't make the mistakes I just did.

Call setVisible only after you have built the UI...

public void run()
{
    frame = new JFrame("Simple Adventure");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(576, 576);
    // frame.setResizable(false);
    getImage();


    c = frame.getContentPane();
    cards = new CardLayout();
    c.setLayout(cards);

    gamepanel = new DrawPanel1();
    gamepanel.setBackground(Color.black);
    c.add(gamepanel, "Panel 1");

    // Lucky last...   
    frame.setVisible(true);
}

Otherwise you will need to revalidate the frame

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