对于我编写的某些代码尝试某些内容有点小问题。我用一个按钮制作了一个框架。当我点击这个按钮,一个新的框架打开,它应该。我关闭新框架,然后再次单击该按钮,尝试查看它是否仍然有效。这个问题从这里开始,科西嘉试图打开一个新的框架,它打开两个新的框架。第三次,我点击它打开4帧等。我尝试了很多东西,但是很遗憾,似乎找不到它打开更多框架的原因。请帮忙。在每次点击时打开双倍数量的新帧
package budget;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame {
String labelPrefix;
JButton button;
JButton button2;
JLabel label;
public static void main(String[] args) {
JFrame f = new GUI();
f.setExtendedState(f.MAXIMIZED_BOTH);
f.setVisible(true);
}
public GUI() {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
button = new JButton("Click Me");
label = new JLabel(labelPrefix);
p.add(button);
this.setTitle("Try");
getContentPane().add(p);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
button.addActionListener(new MyActionListener());
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
button.addActionListener(this);
labelPrefix = "Try";
JFrame f2 = new GUI(label, labelPrefix);
f2.setExtendedState(f2.MAXIMIZED_BOTH);
f2.setVisible(true);
}
}
public GUI(JLabel label, String labelPrefix) {
JPanel p2 = new JPanel();
button2 = new JButton("Close");
p2.add(label);
p2.add(button2);
this.setTitle("Try");
getContentPane().add(p2);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
button2.addActionListener(new MyActionListener2());
}
class MyActionListener2 implements ActionListener {
public void actionPerformed(ActionEvent e) {
button2.addActionListener(this);
dispose();
}
}
}
*“一个新的框架打开,它应该”*要求不同。请参阅[使用多个JFrames,良好/错误的实践?](http://stackoverflow.com/a/9554657/418556) –