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
相关资源:垃圾分类数据集及代码