2014-02-11 41 views
-3

我的代碼有一些奇怪的事情發生。動作按鈕,如果陳述

我有一個小窗體(設計不好,但現在會做)。用戶輸入用戶名和密碼,然後按提交。

我爲按鈕添加了一個動作偵聽器方法。起初,唯一的一件事是:

dispose();

事實上,當按下時,窗戶關閉。

現在,當我添加一個if語句就像你在代碼中看到,它什麼都不做,如果值是正確的,但是,如果這是錯誤的,它做什麼,我在其他部分寫道....

如果我想與& &和passwordfield添加另一個條件,它給我的錯誤信息:該方法已被棄用,而Eclipse提出了gettext的方法輸入密碼線...

我不噸得到它,它如何不工作,如果沒有'如果',不工作'如果',並給我警告與& & ....謝謝...

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"); 
      } 
     }); 


    } 

} 
+0

使用String.equals方法你如果條件比較字符串。 –

+1

字符串比較應該使用.equals()而不是==完成,例如:if(userText.getText()。equals(「ABS」) –

回答

2

你用==比較字符串,而不是平等的()

if (userText.getText().equals("ABC") { 
    ... 
} 
+0

不錯,謝謝,它確實有效,但是,當我這樣做時:if (userText.getText()。equals(「ABC」)&& passwordText.getText()。equals(「1234」))eclipse再次給了我這個警告信息,並在密碼的getText方法上放了一條線 – user3275222

+0

是的。當我通過OOP Basics Java課程時,教師告訴我們絕不要將字符串方法與除equals()方法之外的任何其他字符串方法進行比較+1 – msmolcic

+1

您需要使用'getPassword()'。 /docs.oracle.com/javase/7/docs/api/javax/swing/JPasswordField.html)。總是檢查文檔。 – csmckelvey