I'm not sure if I explained well on the title. So here are the details.
(Down below are my notes if they can help you)
I'm trying to test my skills on Java by creating a Window that will add the Menu JPanel on it when the program starts, and when I call the command to Run the New JPanel Game and remove the JPanel Menu, I have to Minimize the window and get it back to top to see the new JPanel Game panel that I have created.
I have used repaint(); method and setFocusable(true); or setRequestFocusInWindow(); commands directly or from JPanel's or frame window as well like panel.repaint(); etc., but that's not enough. What I'm missing?
I am not gonna be bored and show my entire code, I'll show the only the important lines.
So here I'm creating and calling my First JPanel Menu Window on JFrame.
public class Starting_Window {
public static JFrame frame = new JFrame("The Simple Game By Erick");
public static GameFrameMenu menuG = new GameFrameMenu();
public static PlayingClass game = new PlayingClass();
public static void main(String[] args) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800/4*3);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(menuG);
}
}
So once my code started I have set a contractor for GameFrameMenu so I can add the basics JButtons or anything like that on Menu Panel. So now with few words, this is what happens when the user presses the JButton I have created.
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuTimer.stop();
Starting_Window.menuG.removeAll();
Starting_Window.menuG.repaint();
Starting_Window.frame.repaint();
Starting_Window.frame.add(Starting_Window.game);
Starting_Window.game.setFocusable(true);
Starting_Window.game.repaint();
Starting_Window.frame.remove(Starting_Window.menuG);
}
});
So after that this is my code on PlayingClass:
public class PlayingClass extends JPanel implements ActionListener {
Timer gameTimer;
public PlayingClass() {
setFocusable(true);
setBackground(Color.BLACK);
setLayout(null);
gameTimer = new Timer(10,this);
gameTimer.start();
}
int x = 50, y = 50;
public void paint(Graphics g) {
super.paint(g);
g.fillRect(x, y, 50, 50);
x++;
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
Notes:
I use paint(Graphics g) method on JPanels.
Once I press the button, my screen get's white.
Once I minimize it and get back to it I see the new JPanel that I have added on.
The screen runs normally without bugs.