在我的Swing应用程序中,我有一个带有“添加客户”按钮的MainFrame。当我点击“添加客户”按钮时,我希望在MainFrame消失时显示客户表单。客户表单只有JTabbedPane。 AddCustomerPanel是一个单独的类,只有取消按钮。 AddCustomerPanel已添加到Customer表单的JTabbedPane作为选项卡。当我点击取消按钮时,我希望客户框架消失,主框架再次出现。我尝试使用setVisible()方法。但它没有用。请帮我这样做。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MainFrame extends JFrame{
private JButton btnMain;
MainFrame(){
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
btnMain = new JButton("Add Customer");
btnMain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new Customer().setVisible(true);
this.setVisible(false); // Not working
}
});
add(btnMain);
}
public static void main(String args[]){
new MainFrame();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Customer extends JFrame{
private JTabbedPane tabMain;
Customer(){
setSize(500,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
tabMain = new JTabbedPane();
tabMain.setPreferredSize(new Dimension(490,290));
tabMain.add("Add Customer",new AddCustomerPanel());
add(tabMain);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class AddCustomerPanel extends JPanel{
private JButton btnCancel;
AddCustomerPanel(){
setSize(400,200);
setVisible(true);
setLayout(new FlowLayout());
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
this.setVisible(false); // Not working
new MainFrame().setVisible(true);
}
});
add(btnCancel);
}
}
答案 0 :(得分:1)
我找到了解决方案。
SwingUtilities.getWindowAncestor(this).setVisible(false);
new MainFrame().setVisible(true);