我正在尝试创建一个用户菜单,使用户能够选择不同的选项,尽管程序正在打开我想要的框架,当我按下正确的按钮时,不知怎的,在按下按钮1后,它会弹出相同的框架两次,并在按下下一个按钮后继续这样做。
import javax.swing.*;
import java.awt.event.*;
public class Menu {
public static void main(String[] args) {
JFrame frame = new JFrame("Maze");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1, button2;
button1 = new JButton("Insert a File");
button2 = new JButton("Generate");
panel.add(button1);
panel.add(button2);
button1.addActionListener(new thehandler());
button2.addActionListener(new thehandler2());
thehandler handler = new thehandler();
button1.addActionListener(handler);
thehandler2 handler2 = new thehandler2();
button2.addActionListener(handler2);
}
static class thehandler implements ActionListener {
public void actionPerformed (ActionEvent event) {
JFrame frame2 = new JFrame("Select");
frame2.setVisible(true);
frame2.setSize(300,150);
JPanel panel2 = new JPanel();
frame2.add(panel2);
JButton button3, button4;
button3 = new JButton("Solving");
button4 = new JButton("Play");
panel2.add(button3);
panel2.add(button4);
button3.addActionListener(new thehandler3());
button4.addActionListener(new thehandler4());
thehandler handler3 = new thehandler();
button3.addActionListener(handler3);
thehandler2 handler4 = new thehandler2();
button4.addActionListener(handler4);
}
}
static class thehandler3 implements ActionListener {
public void actionPerformed (ActionEvent event) {
String stringInteger = JOptionPane.showInputDialog(null, "Insert
File: ", "Question", JOptionPane.INFORMATION_MESSAGE);
}
}
static class thehandler4 implements ActionListener {
public void actionPerformed (ActionEvent event) {
String stringInteger = JOptionPane.showInputDialog(null, "Insert
File: ", "Question", JOptionPane.INFORMATION_MESSAGE);
}
}
static class thehandler2 implements ActionListener {
public void actionPerformed (ActionEvent event) {
String stringInteger = JOptionPane.showInputDialog(null, "Insert
the size: ", "Question", JOptionPane.INFORMATION_MESSAGE);
}
}
}
这就是我到目前为止编写的所有代码。 see the problem here 我真的不知道为什么会发生这种情况,并且非常感谢任何解决问题的建议。
最佳答案
这可能是因为您在 JButton
上添加了相同的 ActionListener
两次(不知道为什么要这样做)。现在,由于 JButton
有两个相同的 ActionListener
,因此每次单击都会产生两个框架。
button1.addActionListener(new thehandler());
button2.addActionListener(new thehandler2());
//No need of below lines of codes, these are just repetition of above functionality
/*thehandler handler = new thehandler();
button1.addActionListener(handler);
thehandler2 handler2 = new thehandler2();
button2.addActionListener(handler2); */
您必须在代码中发生此类重复的两处位置进行更改。
关于java - 按下按钮时弹出多个框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953755/