jpanel.add(component) 在 actionListener 中不起作用



我目前还在学习这个叫做摆动的咒语,所以我写了这段代码

lblWarning = new JLabel("<html>Incorrect Username or Password<br/>   please try again!</html>");
lblWarning.setBounds(10,121,220,48);
lblWarning.setForeground(new Color(150, 0, 0));
lblWarning.setBackground(new Color(255, 255, 255));
lblWarning.setFont(new Font("Tahoma", Font.BOLD, 12));

JButton btnNewButton_1 = new JButton("Confirm");
btnNewButton_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 14));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(txtUsername.getText()!="user" && txtPassword.getText()!="pass") {
contentPane.add(lblWarning);
}else {
}
}
});
btnNewButton_1.setBounds(10, 180, 94, 23);
contentPane.add(btnNewButton_1);

txtusername 和 txtpassword 是文本字段,但问题是 contentPane (jpanel( 在条件为真时不会添加标签"lblWarning",但当它在 actionListener 之外时可以工作并显示良好,有什么问题?

  1. 你怎么知道你的"如果条件"是真的?您是否通过添加System.out.println(...)语句来验证是否正在执行语句中的代码,从而执行了基本调试?

  2. 不要使用"=="或"!="来比较字符串。请改用String.equals(...)方法。

  3. 将组件添加到可见框架后,还需要调用panel.revalidate(),以调用布局管理器,以便为组件指定大小/位置。

最新更新