初学java之事件响应(结合接口来设置在同一个界面上!)

处理ACtionEvent事件的Java多线程应用
本文详细介绍了如何使用Java实现处理ActionEvent事件的多线程应用,包括事件监听器的创建、事件源与监视器的关联以及事件处理逻辑的实现。
 1 package wahaha;
 2 
 3 public class test_1 {
 4     public static void main( String args[] )
 5     {
 6         WindowActionEvent win = new WindowActionEvent();
 7         PoliceListen police = new PoliceListen(); //创建监视器
 8         win.setMyCommandListener(police);
 9         win.setBounds(100, 100, 460, 360);
10         win.setTitle("处理ACtionEvent事件");
11     }
12 }
main_class
 1 package wahaha;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5 
 6 public class WindowActionEvent extends JFrame
 7 {
 8     
 9     JTextField inputText ;
10     JTextArea testshow ;
11     JButton button ;
12     MyCommandListener listenner ;
13     
14     public WindowActionEvent()
15     {
16         init();
17         setVisible(true);
18         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19     }
20    
21     void init()
22     {
23       setLayout(new FlowLayout());
24       inputText =new JTextField(10);
25       button =new JButton("确定");
26       testshow = new JTextArea(9,30); 
27       add(inputText);
28       add(button); 
29       add(new JScrollPane(testshow));
30     }
31     
32     void setMyCommandListener(MyCommandListener listener)
33     {
34         this.listenner = listener ;
35         listener.setJTextArea(testshow);
36         listener.setJTextField(inputText);
37                                     //inputText是事件源,listener是监视器      
38         button.addActionListener(listener) ;
39                                     //button是事件源 ,listener是监视器
40     }
41 }
demo
 1  package wahaha;
 2 
 3 //设置一个接口 implements/interface/extends
 4  
 5 import javax.swing.* ;
 6 import java.awt.event.* ;
 7 
 8 public interface MyCommandListener extends ActionListener    //子接口多给出了2个方法
 9 {
10    public void setJTextField(JTextField text);
11    public void setJTextArea(JTextArea area);
12 }
View Code
 1   
 2   package wahaha;
 3 
 4   import javax.swing.*;
 5   import java.awt.event.*;
 6 
 7   public class PoliceListen implements MyCommandListener
 8   {
 9     JTextField textInput ;
10     JTextArea textshow ;
11    
12    public void setJTextField( JTextField text )
13    {
14      textInput = text ;
15    }
16   
17    public void setJTextArea(JTextArea area)
18    {
19        textshow = area;         
20    }
21    
22    public void actionPerformed( ActionEvent e)
23    {    
24        String str=textInput.getText();
25        textshow.append(str+"的长度:"+str.length()+"\n");
26    }
27   }
View Code

转载于:https://www.cnblogs.com/gongxijun/p/3727483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值