我有三个窗口A、B、C,A中有一个按钮能打开B,B中有一个按钮打开C。B、C都是A的内部类。请问我在A中点击按钮打开B后,再把B窗口关掉,接着再点击按钮打开B,再点击B中的按钮,结果弹出了两个C窗口。怎样才能只弹出一个C呢?一下是我的代码
import javax.swing.*;
import java.awt.event.*;
public class CloseWindow extends JFrame{
private JButton button=new JButton("show b");
private void setComponent(){
setTitle("a");
button.addActionListener(new Window1()); //注册打开B窗口
add(button);
pack();
setVisible(true);
}
class Window1 extends JFrame implements ActionListener{
private JButton button2=new JButton("show c");
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("b");
button2.addActionListener(new Window2());//注册打开C窗口
add(button2);
pack();
setVisible(true);
}
}
class Window2 extends JFrame implements ActionListener{
private JLabel label=new JLabel("OK");
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("c");
add(label);
pack();
setVisible(true);
}
}
public static void main(String[] args){
CloseWindow window=new CloseWindow();
window.setComponent();
}
}
------解决方案--------------------
- Java code
public class CloseWindow { JFrame jfa = new JFrame("a"), jfb = new JFrame("b"), jfc = new JFrame("c"); JButton jba = new JButton("showB"), jbb = new JButton("showC"); JTextField jtf = new JTextField("OK" ,20); public void init() { jfa.add(jba); jfb.add(jbb); jfc.add(jtf); jfa.setVisible(true); jfa.pack(); jfa.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); jba.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jfb.setVisible(true); jfb.pack();// TODO Auto-generated method stub jfb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } }); jbb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jfc.setVisible(true); jfc.pack();// TODO Auto-generated method stub jfc.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } }); } public static void main(String...args){ new CloseWindow().init(); }}