简体   繁体   English

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

[英]jpanel.add(component) doesnt work when inside an actionListener

I am currently still learning this spell called swing so i wrote this code我目前仍在学习这个叫做 swing 的咒语所以我写了这段代码

    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 and txtpassword are text fields btw. txtusername 和 txtpassword 是文本字段 btw。 but the problem is contentPane (jpanel) doesnt add the label "lblWarning" when the conditions are true but works and shows fine when its outside the actionListener, whats the problem?但问题是 contentPane (jpanel) 在条件为真时不添加标签“lblWarning”,但在 actionListener 外部时工作并显示正常,问题是什么?

  1. How do you know your "if condition" is ever true?你怎么知道你的“如果条件”永远为真? Did you do basic debugging by adding a System.out.println(...) statement to verify you are executing the code inside the statement?您是否通过添加System.out.println(...)语句来验证您是否正在执行语句中的代码来进行基本调试?

  2. Don't use "==" or ".=" to compare a String.不要使用“==”或“.=”来比较字符串。 Instead use the String.equals(...) method.而是使用String.equals(...)方法。

  3. After you add a component to a visible frame you need to also invoke panel.revalidate() , to invoke the layout manager so the component is given a size/location.将组件添加到可见框架后,您还需要调用panel.revalidate()来调用布局管理器,以便为组件指定大小/位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM