动作按钮和if语句

时间:2014-02-11 15:31:47

标签: java dispose

奇怪的是我的代码。

我有一个小形式(设计不好,但现在会做)。用户键入用户名和密码,然后按“提交”。

我为按钮添加了一个动作侦听器方法。起初,唯一的问题是:

处置();

实际上,当按下时,窗户关闭了。

现在,当我在代码中添加一个if语句时,如果值是正确的,它什么都不做,但是,如果它是错的,它会执行我在else部分写的内容....

如果我试图用&&添加另一个条件和密码字段,它给我错误信息:该方法已被弃用,Eclipse在getText方法上为密码添加了一行......

我没有得到它,如果没有'if'它怎么能工作,不能用'if'工作,并用&& ....给我警告...谢谢...

package HR;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JFormattedTextField;
import javax.swing.JButton;

import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SignIn extends JFrame
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public SignIn()
    {
        this.setTitle("HR SYSTEM LOGIN SCREEN");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(100, 100, 308, 179);

        JPanel contentPane = new JPanel(new GridLayout(3,3,1,15));
        this.getContentPane().add(contentPane);

        JLabel userName = new JLabel("User Name");
        contentPane.add(userName);

        JLabel spaces2 = new JLabel("");
        contentPane.add(spaces2);

        final JFormattedTextField userText = new JFormattedTextField();
        contentPane.add(userText);

        JLabel password = new JLabel("Password");
        contentPane.add(password);

        JLabel spaces3 = new JLabel("");
        contentPane.add(spaces3);

        final JPasswordField passwordText = new JPasswordField();
        contentPane.add(passwordText);

        JLabel spaces1 = new JLabel("");
        contentPane.add(spaces1);

        JButton signButton = new JButton("Sign In");
        contentPane.add(signButton);

        JLabel spaces4 = new JLabel("");
        contentPane.add(spaces4);

        signButton.addActionListener(new ActionListener() 
        {

            @Override
            public void actionPerformed(ActionEvent e) 
            {

                if (userText.getText()=="ABC")
                {
                    dispose();
                }
                else userText.setText("ABC");
            }
        });


    }

}

1 个答案:

答案 0 :(得分:2)

您正在使用==而不是equals()

来比较字符串
if (userText.getText().equals("ABC") {
    ...
}