對自己定義的類規(guī)范化一下,事件和圖形化組件分離出來
定義一個類FrameDemo
定義成員屬性Frame frame
定義成員屬性Botton
定義構(gòu)造方法FrameDemo()
定義初始化方法init()
初始化方法中,new出來Frame(),參數(shù):String的窗體名稱
調(diào)用Frame對象的setBounds()方法,參數(shù):x,y,width,height
調(diào)用Frame對象的setLayout()方法,參數(shù):FlowLayout對象
獲取Button對象,new出來,構(gòu)造參數(shù):String的按鈕文本
調(diào)用Frame對象的add()方法,參數(shù):Button對象
調(diào)用Frame對象的setVisible()方法,參數(shù):Boolean的true
定義事件方法myEvent()
調(diào)用Frame對象的addWindowListener()方法,參數(shù):WindowListener對象,WindowListener是個接口,里面有七個方法要實現(xiàn),找實現(xiàn)子類WindowAdapter,匿名內(nèi)部類重寫windowClosing()方法,傳遞進來參數(shù):WindowEvent對象
調(diào)用Button對象的addActionListener()方法,參數(shù):ActionListener對象,這個類是個接口,因此采用匿名內(nèi)部類實現(xiàn)這個接口,實現(xiàn)方法actionPerformed()方法,傳遞進來參數(shù):ActionEvent對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class FrameDemo { private Frame frame; private Button button; public FrameDemo() { init(); } /** * 初始化 */ public void init(){ frame= new Frame( "測試窗體" ); frame.setBounds( 300 , 200 , 200 , 200 ); frame.setLayout( new FlowLayout()); button= new Button( "退出" ); frame.add(button); frame.setVisible( true ); addEventAction(); } /** * 添加事件 */ public void addEventAction(){ //按鈕退出 button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit( 0 ); } }); } /** * @param args */ public static void main(String[] args) { new FrameDemo(); } } |
以上這篇淺談javaSE GUI (Action事件)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務器之家。