java关闭和重新显示帧的频率随着每次按下按钮的频率的增加而增加
我正在使用自制的工具栏浏览我的应用程序,该工具栏显示在所有页面上。每次显示新页面时,我都会使用以下代码关闭当前帧并打开新帧:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
我这样做是因为ActionListeners是在toolbar类中声明的,而每个页面的框架是在运行时声明的,不是静态的
除了一个特殊情况“取消”按钮外,这一切都可以正常工作,第一次访问帧时,它将关闭一次。第二次将关闭并重新打开2次,第三次将关闭并重新打开3次,依此类推。我使用代码中的“计数器”跟踪了这一点
我已将代码最小化,以重新创建相同的行为,如下所示:
工具栏类
public class Toolbar {
static JButton buttonCancel = new JButton("Cancel");
static int counter;
public static JPanel Toolbar(String panelname){
FlowLayout layout = new FlowLayout();
JPanel Toolbar = new JPanel(new BorderLayout());
Toolbar.setLayout(layout);
GridLayout GLayout = new GridLayout(2,1);
GLayout.setVgap(0);
JPanel container2 = new JPanel();
if(panelname.matches("Customers")){
container2.setLayout(GLayout);
JButton buttonAddCust = new JButton("Add Cust");
container2.add(buttonAddCust, BorderLayout.PAGE_START);
buttonAddCust.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
Customers.AddCustomersGui();
}
});
}
JPanel container21 = new JPanel();
if(panelname.matches("Add Customers")){
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter ++;
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
}
Toolbar.add(container2);
Toolbar.add(container21);
return Toolbar;
}
}
GUI类
public class Customers extends Toolbar{
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(Toolbar.Toolbar(frame.getTitle()));
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void AddCustomersGui(){
final JFrame frame1 = new JFrame("Add Customers");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Addcustomers = new JPanel();
Addcustomers.add(Toolbar.Toolbar(frame1.getTitle()));
frame1.setContentPane(Addcustomers);
frame1.setSize(1200,500);
frame1.setVisible(true);
}
}
主类
public static void main(String[] args) {
Customers.CustomersGui();
}
# 1 楼答案
随着代码的每次迭代,您将向buttonCancel添加一个新的ActionListener,这就是程序行为的原因
另外,根据我的评论,你说
更好的设计可能不是交换可能令人讨厌的窗口,而是使用CardLayout交换JPanel视图。请阅读The Use of Multiple JFrames, Good/Bad Practice?
例如,将这行代码添加到程序中:
您将看到ActionListeners被多次添加到此按钮
交换视图的一个示例: