Basic Problem: I created a Game with 3 "States", each State is started by a method within the same Class. Each Method calls panel.removeAll(); on the static panel, that shows the game content and then i add the buttons, background etc again to the Panel. In the first "Loop" (by "loop" i mean the sequence of all 3 States where called once by each other, everything works just fine.
When State 3 calls State 1 again, so when the second Loop starts the following problem occurs: When i hit a JButton, the Action is performed TWICE. In the third loop its performed three times!
So whats my Problem in here? Is it so, that i add the buttons multiple times, by removeAll() and panel.add(JButton) again?
If so, whats the way around it? Should i create different Panels and set them invisible/visible one at a time? Wouldnt that cause heavy "Weight" on the processor by having all graphics loaded all the time?
Thanks for your Help!
EDIT: Here is an example:
package sscc;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class stuff extends JFrame implements ActionListener {
static stuff frame = new stuff();
static JPanel panel = new JPanel();
public static void main(String[] args){
//Setting up the Frame in MainMethod. Is that wrong?
frame.setSize(800, 600);
frame.setResizable(false);
frame.setLocationRelativeTo ( null );
frame.setUndecorated(true);
frame.add(panel); //
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.Phase1();
}
//Each Phase gets a Button to Enter the next one
JButton Next1 = new JButton("Next1");
JButton Next2 = new JButton("Next2");
JButton Next3 = new JButton("Next3");
public void Phase1(){
panel.removeAll();
panel.add(Next1);
Next1.setBounds(200,200,200,200);
Next1.setActionCommand("Phase1");
Next1.addActionListener(this);
}
public void Phase2(){
panel.removeAll();
panel.add(Next2);
Next2.setBounds(200,200,200,200);
Next2.setActionCommand("Phase2");
Next2.addActionListener(this);
}
public void Phase3(){
panel.removeAll();
panel.add(Next3);
Next3.setBounds(200,200,200,200);
Next3.setActionCommand("Phase3");
Next3.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if("Phase1".equals(e.getActionCommand())){System.out.println("Phase1Counter");Phase2();}
if("Phase2".equals(e.getActionCommand())){System.out.println("Phase2Counter");Phase3();}
if("Phase1".equals(e.getActionCommand())){System.out.println("Phase3Counter");Phase1();}
}
}