簡體   English   中英

當我按下JButton它檢查你是否輸入JTextFeild中的內容是對還是錯時,我怎么能這樣做呢? (就像Java中的鎖一樣)

[英]How can I make it so when I press a JButton it checks whether you entered something in JTextFeild is right or wrong? (Just like a lock in Java)

很抱歉,如果這個問題已在某個地方得到解答,或者我沒有意義,但我想知道我是否可以在JPanel上創建“鎖定”。 到目前為止,我已經做到了這一點,當我按下按鈕時它會清除所有內容並出現JLabel。 但是,當我在JTextField中鍵入內容時,我無法做到這一點,JAVA會檢查我在文本字段中輸入的內容是否與“正確”用戶名匹配。 我可以讓JLabel出現的唯一方法是通過控制台,我不希望這種情況發生。 當我在JTextField中鍵入內容進行檢查時,我想要它。 我聽說你可以在按鈕中添加KeyListener或addActionListener,但是如何實現呢?

再一次,我只是JAVA的初學者,我不確定我做錯了什么,但我只是感到困惑,所以如果你能幫助我,那將非常感激!

這是我的代碼

package Story;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

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

import java.util.Scanner;

@SuppressWarnings("unused")
public class Login {

public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);

frame.setVisible(true);

}

private static void placeComponents(JPanel panel) {

panel.setLayout(null);

JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);

JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);

JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);

JButton registerButton = new JButton("register");
registerButton.setBounds(180, 80, 80, 25);
panel.add(registerButton);


   loginButton.addActionListener(new ActionListener() 
   {
        public void actionPerformed(ActionEvent e) {

           loginButton.setVisible(false);

           registerButton.setVisible(false);

           userText.setVisible(false);

           userLabel.setVisible(false);

@SuppressWarnings("resource")
Scanner user = new Scanner (System.in);
String name = user.nextLine();
String accept = "Kenny";
String good; 

if (name.equals(accept)) {
good = "Welcome";

} else {
good = "False. Error";
} 
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
       label1.setVisible(true);           
       panel.add(label1);

}


   });
}
}

你在檢查時從控制台獲取輸入,那么你對你的預期結果如何?

更改以下行:

String name = user.nextLine();

String name = userText.getText();

您應該獲得用戶輸入的文本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM