/**
* ActionListener:按钮监听事件
* @author Administrator
*/
public class ActionListenerDemo{
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("窗口程序");//创建一个带标题的窗口对象frame
frame.setVisible(true);//显示窗口
frame.setSize(600, 400);//设置窗口大小
frame.setLocationRelativeTo(null);//设置窗口居中
frame.setDefaultCloseOperation(3);//点击X关闭程序 3为结束程序
frame.setLayout(null);//清空布局
TextField textField = new TextField();
textField.setBounds(40, 20, frame.getWidth()-100, 50);
textField.setBackground(Color.white);
MyActionListener myActionListener = new MyActionListener(textField);//创建一个按钮监听事件对象
frame.add(textField);
Button button = new Button("按钮");
button.setBounds(100,100,100,100);
button.setBackground(Color.orange);
button.addActionListener(myActionListener);//添加myActionListener监听事件
frame.add(button);
}
}
class MyActionListener implements ActionListener{
private TextField textField;
int count;
public MyActionListener(TextField textField) {
super();
this.textField = textField;
}
每按一次按钮,此方法都会自动调用一次
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
count++;
textField.setText("你点击了按钮 "+ count + " 次");
}
}