我有一个 JFrame,其初始化如下:
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(PREFERRED_SIZE);
setTitle("Game Set");
setLayout(new BorderLayout());
background = new JLabel(new ImageIcon("images/gameSetBackground.jpg"));
background.setPreferredSize(PREFERRED_SIZE);
add(background);
loginPane = new LoginPane();
background.setLayout(new GridBagLayout());
loginPane.setOpaque(false);
background.add(loginPane, constraints);
pack();
setVisible(true);
我这样做是因为它让我将背景设置为我指定的 jpg。现在我有 loginPane() 类,如下所示:
public class LoginPane extends JPanel {
JLabel label = new JLabel("Login");
JLabel secondLabel = new JLabel("If you don't have a profile, click below to create one!");
JTextField userName;
JPasswordField password;
public LoginPane() {
setLayout(new GridBagLayout());
userName = new JTextField(20);
password = new JPasswordField(20);
constraints.insets = new Insets(2, 2, 2, 2);
constraints.gridx = 0;
constraints.gridy = 0;
add(label, constraints);
// etc add all of them the same way
constraints.gridy = 3;
add(secondLabel, constraints);
userName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
password.requestFocus();
}
});
password.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (userName.getText().equals("Mike")) {
}
}
});
}
}
我想要发生的是,当我输入用户名和密码后按回车键时,我将检查这是否是有效的用户名/密码对。之后,我想删除此处的所有内容并显示不同的 JPanel
。在password.ActionListener中,我尝试了以下操作:
loginPane.removeAll();
background.removeAll();
这是两个不同的情况,但都导致 JFrame 崩溃,TextFields 变得无响应,我必须退出。我做错了什么?
最佳答案
"JFrame crashes when trying to replace a panel with another panel"
简单/正确的解决方案是使用 CardLayout
在面板之间切换。查看更多How to use CardLayout并查看一个简单的示例 here .
CardLayout
具有 show()
等方法来按名称显示某个面板,next()
来显示下一个面板,和 previous()
显示上一个面板。这是优于删除和添加面板的首选方式。
关于java - 尝试用另一个面板替换一个面板时 JFrame 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23393666/