我已经搜索过,但我没有找到我理解的答案。目前,我发现一些帖子询问有关触发所有事件等问题,但我只需要触发一个事件。此代码用于登录框。
编辑:我需要由“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();
}
}