Solved: JFrame - Problem with changing JPanel

Hi, we got a problem,


//Main-Class;

public void actionPerformed(ActionEvent e){
		
		if (e.getSource() == mainMenuButtons[0]) {
			
			try {
				GameWindow.gw.setLoadingPanel();
			} catch (IOException e2) {
				e2.printStackTrace();
			}
			
			PictureIds.setObjectPictureIds();
			PictureIds.setTerrainPictureIds();
			
			try {
				GameWindow.gw.setGamePanel();
			} catch (IOException e1) {
				e1.printStackTrace();
			}


//Game-Window-class

	public void setLoadingPanel() throws IOException{
		GameWindow.this.getContentPane().removeAll();
		lpanel = new LoadingPanel();
		this.add(lpanel);
		this.validate();
		this.repaint();
		lpanel.grabFocus();
		lpanel.repaint();
	}


//LoadingPanel-class

	public LoadingPanel() {
		super();
		this.setFocusable(true);
		this.grabFocus();
		System.out.println("Loading Const.");
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		System.out.println("Loading");
		g.drawImage(loadingScreen, 0, 0, null);
		g.dispose();
	}
}

//GamePanel-class
	public GamePanel() throws IOException {
		super();
		moveThread = new MoveThread(this);
		Thread start = new Thread(moveThread);
		start.start();
........
}




Our problem is that the paint-method in LoadingPanel-class is never called. If you comment GameWindow.gw.setGamePanel() out, “PictureIds.setObjectPictureIds() PictureIds.setTerrainPictureIds();” are both called before the paint-method in the LoadingPanel-class.
It should repaint after the constructor of LoadingPanel, and before the other methods are called because a loading-screen which is called after the loading is quite useless.
best regards

That’s because the LoadingPanel is never even shown at all. You set the LoadingPanel, load the resources, then set the GamePanel in the same method. Even worse, that method is called on the EDT (Event Dispatch Thread), which controls events such as repainting, action events, etc…

The solution would be to create a new thread that loads the resources, then notifies the EDT to set the GamePanel once it is done :slight_smile:

EDIT: Ah you seem to believe that ‘repaint()’ blocks until it repaints the screen. Sadly it is not so. What it actually does is post a repaint event on the EDT queue. This means that the EDT will repaint the screen as soon as it is done with all the other tasks, such as returning from that actionPerformed method. :wink:

Thx, I will have a try :slight_smile:

Edit:
Worked ;D

I’m making the game together with Phibedy.
We’re now loading all recources (png’s, Maps, Objects, Players…ect. ) in a new Thread. Everything works as it should (even the loading screen :wink: )

Thanks,
twinflyer