![](/img/trans.png)
[英]NullPointerException when trying to getText from another panel
[英]JFrame crashes when trying to replace a panel with another panel
我有一个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")) {
}
}
});
}
}
我想发生的是,在输入用户名和密码后,按Enter键时,我将检查该用户名/密码对是否有效。 之后,我要删除此处的所有内容并显示不同的JPanel
。 在password.ActionListener内部,我尝试了以下操作:
loginPane.removeAll();
background.removeAll();
那是两种不同的情况,但是都导致JFrame崩溃,TextFields变得无响应,我不得不退出。 我究竟做错了什么?
“尝试用另一个面板替换面板时,JFrame崩溃”
简单/正确的解决方案是使用CardLayout
在面板之间切换。 在如何使用CardLayout中查看更多信息,并在此处查看一个简单示例。
CardLayout
具有诸如show()
来按名称显示某个面板, next()
来显示下一个面板以及previous()
来显示前一个面板的方法。 与删除和添加面板相比,这是首选方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.