javaSwing事件监听与处理

 1 package ch11_2;
 2 
 3 import java.awt.*;
 4 
 5 import javax.swing.*;
 6 
 7 public class MyButtonFrame extends JFrame {
 8 
 9     private JButton btn;
10     private JTextField tf;
11 
12     public MyButtonFrame(String s) {
13         super(s);
14         this.setSize(900, 300);
15         this.setLocation(500, 500);
16         btn = new JButton("点击");// 创建按钮对象,为事件源
17         tf = new JTextField(50);
18         this.setLayout(new FlowLayout());
19         this.add(btn);// 向窗体中添加按钮对象
20         this.add(tf);// 向窗体中添加文本对象
21         // 事件监听器创建和注册
22         ButtonListener bl = new ButtonListener(this);
23         btn.addActionListener(bl);
24     }
25 
26     public JTextField getTf() {//为了在监听器类中获取文本框对象
27         
28         return tf;
29     }
30 
31 }
 1 package ch11_2;
 2 
 3 import java.awt.event.*;
 4 
 5 import javax.swing.*;
 6 
 7 public  class ButtonListener implements ActionListener {
 8 
 9     private MyButtonFrame jf;// 利用该属性获取窗体中组件对象
10 
11     public ButtonListener(MyButtonFrame jf) {
12         super();
13         this.jf = jf;
14     }
15 
16     @Override
17     public void actionPerformed(java.awt.event.ActionEvent e) {
18         JTextField tf = jf.getTf();
19         tf.setText("我知道你按下按钮啦!");
20     }
21 
22 
23 }
 1 package ch11_2;
 2 import javax.swing.JFrame;
 3 
 4 public class ActionEvent {
 5 
 6     public static void main(String[] args) {
 7         MyButtonFrame frm=new MyButtonFrame("命令按钮事件处理示例");
 8         frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 9         frm.setVisible(true);
10     }
11 
12 }

 

posted @ 2020-12-22 16:17  丁帅帅dss  阅读(500)  评论(0)    收藏  举报