'Java button, switch to another frame, closing current frame and running a method in another class
I have tried creating a button "Menu", and on click it closed the frame that it's on, open a class StartWindow, after that it would use a method "Menu", without running method "Welcome". But in stead it doesn't close the frame, but also runs just the class, which at first runs only method "Welcome"
Button:
menu.setBounds(1, 1, 65, 65);
menu.setFocusable(false);
menu.setText("Menu");
menu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent j) {
if(j.getSource() == menu) {
StartWindow menu = new StartWindow();
frame.dispose();
menu.Menu(frame);
}
}
});
Constructor
StartWindow(){ JFrame frame = new JFrame();
frame.setSize(420, 420);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Welcome(frame);
}
Method:
```Java
public void Menu(JFrame frame){
JPanel panel1 = new JPanel();
JTextField text1= new JTextField();
JTextField text2= new JTextField();
JButton button1= new JButton();
JButton button2= new JButton();
panel1.setLayout(null);
panel1.setSize(420, 420);
panel1.setBackground(new Color(212, 190, 190));
text1.setText("With friends");
text1.setBackground(new Color(212, 190, 190));
text1.setBounds(140, 60, 65, 40);
text1.setBorder(null);
text1.setFocusable(false);
text1.setEditable(false);
text2.setText("With AI");
text2.setBackground(new Color(212, 190, 190));
text2.setBounds(140, 132, 65, 40);
text2.setBorder(null);
text2.setEditable(false);
text2.setFocusable(false);
//With friend
button1.setBounds(140, 100, 85, 32);
button1.setBackground(new Color(212, 190, 190));
button1.setFocusable(false);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent a) {
if(a.getSource() == button1) {
frame.dispose();
new TTT_1();
}
}
});
button1.setBorder(new RoundedBorder(10));
button1.setText("1 VS 1");
//AI
button2.setBounds(140, 172, 75, 32);
button2.setBackground(new Color(212, 190, 190));
button2.setFocusable(false);
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent b) {
if(b.getSource() == button2) {
frame.dispose();
new TTT_2();
}
}
});
button2.setBorder(new RoundedBorder(10));
button2.setText("AI");
panel1.add(text1);
panel1.add(text2);
panel1.add(button1);
panel1.add(button2);
frame.add(panel1);
frame.setVisible(true);
}
I had a few theories on what is wrong, one of them is the constructor that it can be redesigned and it will solve my problem, another was that there is something wrong in the button.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
