我正在尝试做一些非常简单的事情,在点击按钮时更改按钮中的文字。
我似乎无法让它工作,有人能告诉我添加ActionListener的正确位置吗?
主要类
public class ATM implements ActionListener{
public static void main(String[] args) {
atmGUI gui = new atmGUI();
gui.login();
}
}
atmGUI课程
public class atmGUI implements ActionListener {
public JTextField usernameField;
public JTextField pinField;
public String userName;
public int pin;
/**
* @wbp.parser.entryPoint
*/
public void login() {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setTitle("Virtual Bank Account");
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(16, 88, 82, 16);
frame.getContentPane().add(lblUsername);
usernameField = new JTextField();
usernameField.setBounds(13, 107, 124, 28);
frame.getContentPane().add(usernameField);
usernameField.setColumns(10);
JLabel lblPin = new JLabel("PIN");
lblPin.setBounds(16, 140, 61, 16);
frame.getContentPane().add(lblPin);
pinField = new JTextField();
pinField.setBounds(13, 157, 124, 28);
frame.getContentPane().add(pinField);
pinField.setColumns(10);
JButton btnLogin = new JButton("Login");
btnLogin.setBounds(355, 232, 117, 29);
btnLogin.addActionListener(new ActionListener(){
btnLogin.setText("Clicked");
});
frame.getContentPane().add(btnLogin);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
}
编辑:
以下是产生的错误
新的ActionListener(){}类型必须实现继承的抽象方法ActionListener.actionPerformed(ActionEvent)
答案 0 :(得分:2)
添加匿名函数
btnLogin.addActionListener(new ActionListener(){
//do something
//lblUsername.setText("blah blah");
});
详情:
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something
//lblUsername.setText("blah blah");
}
});
答案 1 :(得分:1)
您应该在atmGUI类中实现actionperformed()方法来处理点击的操作。
答案 2 :(得分:1)
您需要将onActionPerformed(ActionEvent)
方法添加到atmgui
课程中,如下所示:
public void onActionPerformed(ActionEvent avt)
{
//code to handle the button click
}
OR
您也可以在初始化JButton
时使用它:
JButton b=new JButton("Click Me!" );
b.addActionListener(new ActionListener() {
//handle the button click here
}