我搜索了,但我沒有找到我明白的答案。目前,我找到了關於觸發所有事件等問題的帖子,但我只需要觸發一個事件。此代碼適用於登錄框。使用JFrame,我怎樣才能讓輸入鍵觸發與按下按鈕相同的結果?
編輯:我需要按「ENTER」觸發的按鈕是登錄按鈕。
這裏是我的代碼:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.IOException;
import java.io.Serializable;
/**
* Write a description of class Login here.
*
* @author()
* @version()
*/
public class LoginFrame extends JFrame
{
private JTextField statusField = new JTextField(20);
private JTextField usernameField = new JTextField(10);
private String usernameText;
private JTextField passwordField = new JTextField(10);
private String passwordText;
private JButton loginButton = new JButton("Log in");
private JButton cancelButton = new JButton("Cancel");
public static void main() {
LoginFrame app = new LoginFrame();
app.setVisible(true);
app.setLocationRelativeTo(null);
}
public LoginFrame() {
super("Login");
statusField.setText("Enter Username and Password");
statusField.setHorizontalAlignment(JLabel.CENTER);
statusField.setEditable(false);
add(statusField, BorderLayout.NORTH);
JPanel p = new JPanel();
p.setLayout(new GridLayout(2, 2));
p.add(new JLabel("User name:"));
p.add(usernameField);
usernameText = usernameField.getText();
p.add(new JLabel("Password:"));
p.add(passwordField);
passwordText =passwordField.getText();
add(p, BorderLayout.CENTER);
Box buttonBar = Box.createHorizontalBox();
buttonBar.add(Box.createHorizontalGlue());
buttonBar.add(cancelButton);
buttonBar.add(Box.createHorizontalGlue());
buttonBar.add(loginButton);
buttonBar.add(Box.createHorizontalGlue());
add(buttonBar, BorderLayout.SOUTH);
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent cancel) {
System.exit(0);
}
});
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent login) {
statusField.setText("Authenticating...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
//Handle exception
}
if ((usernameText == "abc") && (passwordText == "123"))
{
statusField.setText("Valid Username and Password");
}
else
{
statusField.setText("Invalid: Locked Out");
usernameField.setEditable(false);
passwordField.setEditable(false);
}
}
});
p.setPreferredSize(new Dimension(335, 55));
pack();
}
}
'我搜索了,但我還沒有找到答案,我明白' - 所以張貼您不明白的代碼或發佈鏈接到您不明白的頁面。我們不介意讀者。我們不知道你不明白。我們不想浪費時間提出相同的建議。 '但我只需要觸發一個事件' - 你是什麼意思,你只需要觸發一個事件?你有兩個按鈕。你是否想要默認觸發「登錄」按鈕,即使它沒有焦點?還是你想讓按鈕觸發,當它確實有焦點? – camickr