【问题标题】:jpanel.add(component) doesnt work when inside an actionListenerjpanel.add(component) 在 actionListener 中不起作用
【发布时间】:2019-11-30 21:57:35
【问题描述】:

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

    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 之外时工作并显示正常,有什么问题?

【问题讨论】:

  • 按钮 btnNewButton_1 未添加到任何其他组件。你要点击它吗?
  • 如果你的意思是这个 contentPane.add(btnNewButton_1);然后它就在那里,我只是忘了在这里粘贴它
  • 不要使用 setBounds()。 Swing 旨在与布局管理器一起使用。在提出问题时发布正确的minimal reproducible example,以便我们更好地了解您的代码上下文。

标签: java swing jpanel jlabel


【解决方案1】:
  1. 您如何知道您的“如果条件”是否为真?您是否通过添加System.out.println(...) 语句来验证您正在执行语句中的代码来进行基本调试?

  2. 不要使用“==”或“!=”来比较字符串。而是使用String.equals(...) 方法。

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

【讨论】:

  • 对于你的第一个问题,我这样做了` btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { contentPane.add(lblWarning); } }); ` 它仍然没有工作 3- 如果你的意思是 ` public void actionPerformed(ActionEvent arg0) { contentPane.add(lblWarning); contentPane.revalidate(); } }); `它也没有工作
  • 不要在 cmets 中发布代码。代码不可读。更新您的代码,显示您如何实施所有 3 条建议。并将代码更新为minimal reproducible example。那就是发布包含框架、两个文本字段和按钮的演示,这样我们就可以准确地看到你在做什么。我们应该能够复制/粘贴/编译和测试代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多