Java JPanel not appearing



我有两个jpanel,一个显示为主页/欢迎页面,另一个在用户单击按钮时显示。当按钮被点击时,第一个面板不会消失,第二个面板同时显示其组件,因此有两个面板的按钮/文本字段等同时可见。

如何解决这个问题,使panel1消失/panel2出现?

(如果在单击按钮后将容器可见性设置为false,则两个面板的组件都不显示。)

public class mainApplication {
private static JFrame mainApp;
private static JPanel panel1;
private static JPanel panel2;
public mainApplication() {
JFrame.setDefaultLookAndFeelDecorated(true);
mainApp = new JFrame("Keystroke Authenticator Application");
mainApp.setSize(640, 480);
mainApp.setLocationRelativeTo(null);
mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainApp.add(panel1());
mainApp.setVisible(true);
}
private JPanel panel1() {
panel1 = new JPanel();
panel1.setSize(640,480);
Container contain1 = mainApp.getContentPane();
//Buttons, text fields and labels are configured with groupLayout here
panel1.setVisible(true);
buttonNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent clickNew) {
panel2 = panel2();
panel1.setVisible(false);
//contain1.setVisible(false); - neither panel are displayed
}
}
);
return panel1;
}
private JPanel panel2() {
panel2 = new JPanel();
panel2.setSize(640,480);
Container contain2 = mainApp.getContentPane();
//Buttons, text fields and labels are configured with groupLayout here
panel2.setVisible(true);
mainApp.add(panel2);
}
}

我解决了我自己的问题,这似乎是我在每个JPanel中创建一个容器并将其与GroupLayout一起使用的事实。我删除了创建的容器,并用JPanel的名称替换了容器:

//working code
GroupLayout layout = new GroupLayout(panel1);
panel1.setLayout(layout);
//instead of the original below
GroupLayout layout = new GroupLayout(container1);
container1.setLayout(layout);

我建议使用布局管理器;这应该能解决你的大部分问题。

public mainApplication() {
//normal formatting stuff
mainApp.setLayout(new FlowLayout()); //This will make things appear/disappear
mainApp.setResizable(false) //This will stop your frame from changing sizes on you
}
private JPanel panel1(JFrame frame) {
//normal formatting stuff
frame.add(panel1); //this will make your panel appear in the frame
//more formatting stuff and button creation
buttonNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel2 = panel2();
frame.remove(panel1); 
frame.add(panel2);
frame.pack(); //this swaps out your components so that the frame displays panel2 instead. Pack makes it repaint itself.
}
return panel1;
}

基本上,你所做的是告诉框架去画第一个面板,但然后你告诉它用面板2来画,从来没有说过停止画面板1。使用布局管理器在幕后处理所有这些,并从长远来看有助于其他事情。

最新更新