Java基礎——GUI編程(二),java基礎gui編程

來源:互聯網
上載者:User

Java基礎——GUI編程(二),java基礎gui編程

一、事件監聽機制

-- 事件來源:awt 或swing包中的那些圖形介面組件,即發生事件的組件

-- 事件:Event  使用者對組件的一個操作

-- 監聽器:Listener  負責處理事件的方法

二、java.awt.event 包下的類

WindowEvent  //視窗事件,比如使用者點了半閉視窗,視窗得到或失去焦點,最大化最小化等

MouseEvent  //滑鼠事件,滑鼠按下,滑鼠釋放,點擊(按下後再鬆開)等

ActionEvent  //動作事件,它不是代表一個具體動作,而是一種語義,比如按紐,或菜單被點擊,在文字框中按下斷行符號等,可以這樣理解:使用者的某一動作導致了某個組件本身的基本作用發生了,這就是ActionEvent事件

不同的事件類型,對應著不同的事件監聽器介面,介面的名稱和事件的名稱是相對應的。

WindowEvent - >WindowListener

MouseEvent ->MouseListener

ActionEvent ->ActionListener

程式碼範例:

import java.awt.Frame;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;public class Test20 {    public static void main(String[] args) {        Frame f = new Frame();        f.setSize(400, 400);        f.setVisible(true);        f.addWindowListener(new WindowListener() {            @Override            public void windowOpened(WindowEvent e) { // 視窗被開啟                // TODO Auto-generated method stub            }            @Override            public void windowClosing(WindowEvent e) { // 設定關閉事件                // TODO Auto-generated method stub                System.exit(0);            }            @Override            public void windowClosed(WindowEvent e) { // 使用者已經關閉視窗                // TODO Auto-generated method stub            }            @Override            public void windowIconified(WindowEvent e) { // 被最小化的時候                // TODO Auto-generated method stub            }            @Override            public void windowDeiconified(WindowEvent e) { // 最小化被還原的時候                // TODO Auto-generated method stub            }            @Override            public void windowActivated(WindowEvent e) { // 表單被啟用                // TODO Auto-generated method stub            }            @Override            public void windowDeactivated(WindowEvent e) { // 失去焦點的時候                // TODO Auto-generated method stub            }        });    }}

有沒有發現,用WindowListener介面的時候,會引入一大堆不常用的代碼(這裡我們只想設定關閉),借口裡的方法只能被覆蓋,又不能刪掉,這樣就是的整個項目顯得很羅嗦,為瞭解決這個事情,就有了事件適配器。

三、事件適配器

JDK 針對大多數事件監聽器介面類定義了相應的實作類別(裡面有很多空實現的方法,方便我們建立接聽程式對象),我們稱為事件適配器類。這裡我用到了WindowAdapter。

import java.awt.Frame;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class Test21 {    public static void main(String[] args) {        Frame f = new Frame("事件適配器的栗子");        f.setSize(400, 400);        f.setVisible(true);        f.addWindowListener(new WindowAdapter() {            public void windowClosing(WindowEvent e) {                System.exit(0);            }        });    }}

可以觀察一下WindowAdapter類的源碼,找找感覺。

public abstract class WindowAdapter    implements WindowListener, WindowStateListener, WindowFocusListener{    /**     * Invoked when a window has been opened.     */    public void windowOpened(WindowEvent e) {}    /**     * Invoked when a window is in the process of being closed.     * The close operation can be overridden at this point.     */    public void windowClosing(WindowEvent e) {}    /**     * Invoked when a window has been closed.     */    public void windowClosed(WindowEvent e) {}    /**     * Invoked when a window is iconified.     */    public void windowIconified(WindowEvent e) {}    /**     * Invoked when a window is de-iconified.     */    public void windowDeiconified(WindowEvent e) {}    /**     * Invoked when a window is activated.     */    public void windowActivated(WindowEvent e) {}    /**     * Invoked when a window is de-activated.     */    public void windowDeactivated(WindowEvent e) {}    /**     * Invoked when a window state is changed.     * @since 1.4     */    public void windowStateChanged(WindowEvent e) {}    /**     * Invoked when the Window is set to be the focused Window, which means     * that the Window, or one of its subcomponents, will receive keyboard     * events.     *     * @since 1.4     */    public void windowGainedFocus(WindowEvent e) {}    /**     * Invoked when the Window is no longer the focused Window, which means     * that keyboard events will no longer be delivered to the Window or any of     * its subcomponents.     *     * @since 1.4     */    public void windowLostFocus(WindowEvent e) {}}

練習幾個個事件處理常式的栗子吧。

例一:

import java.awt.Button;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;//例一:在表單中放置一個按紐,點擊後讓程式退出class TestFrame implements ActionListener { // ActionListener介面裡面只有一個方法,下面會重寫    private Frame f;    public TestFrame() {        f = new Frame("視窗");        init();    }    private void init() {        f.setSize(300, 300);        f.setLayout(new FlowLayout());// 配置模式        Button b = new Button("退出程式");        b.addActionListener(this);        f.add(b);        f.setVisible(true);    }    @Override    public void actionPerformed(ActionEvent e) {        // TODO Auto-generated method stub        f.setVisible(false);        f.dispose();// 在關閉的時候,可以用它來銷毀表單資源        System.exit(0);// 退出    }}public class Test22 {    public static void main(String[] args) {        new TestFrame();    }}

上面的,點擊退出程式按鈕才可以退出,點擊右上方的X,是不可以退出的哦。因為沒有設定WindowListener哦。

這個例子用到ActionListener介面,可以看一下它的原始碼,如下:

public interface ActionListener extends EventListener {    /**     * Invoked when an action occurs.     */    public void actionPerformed(ActionEvent e);}

例二:

import java.awt.Color;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.TextField;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;//在表單中,放置一個文字框,能過濾非法字元( 除了數字以外的 ) public class TestFrame {    private Frame f;    private TextField txtNo;// TextField代表文字框    public TestFrame() {        f = new Frame("請輸入密碼");                //f.setBackground(red);這裡我自己試的, 沒成功
f.setBackground(Color.red);//這樣就可以了
f.setBounds(50, 50, 400, 400);// 設定視窗座標和大小 f.setLayout(new FlowLayout());// 設定表單布局 txtNo = new TextField(10);// 設定輸入視窗的顯示長度。輸入的內容長度沒有界限 f.add(txtNo); txtNo.addKeyListener(new KeyAdapter() { // 從JDk中粘貼過來這個方法來用 public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (!(code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9)) {// 設定輸入內容為0-9 System.out.println(KeyEvent.getKeyText(code) + "輸入有誤"); e.consume(); } } }); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); System.exit(0); } }); }}

測試類別:

public class Test23 {    public static void main(String[] args) {        new TestFrame();    }}

例三:

列出指定目錄的內容:

import java.awt.Button;import java.awt.FlowLayout;import java.awt.Frame;import java.awt.TextArea;import java.awt.TextField;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;public class Test24 {    public static void main(String[] args) {        new MyWindow();    }}class MyWindow {    MyWindow() {        init();    }    private Frame f;    private Button b;    private TextField txtDir;// 用來輸入目錄名稱    private TextArea txtFileList;// 用來顯示檔案清單    private void init() {        f = new Frame("視窗");        f.setBounds(44, 44, 500, 500);        f.setLayout(new FlowLayout());        txtDir = new TextField(8);        b = new Button("顯示");        txtFileList = new TextArea(20, 30);// 用來顯示檔案清單的地區        f.add(txtDir);        f.add(b);        f.add(txtFileList);        initEvent();        f.setVisible(true);    }    private void initEvent() {        // TODO Auto-generated method stub        f.addWindowListener(new WindowAdapter() {            /**             * Invoked when a window is in the process of being closed. The             * close operation can be overridden at this point.             */            public void windowClosing(WindowEvent e) {                System.exit(0);            }        });        b.addActionListener(new ActionListener() {            /**             * Invoked when an action occurs.             */            public void actionPerformed(ActionEvent e) {                txtFileList.setText("");                String dirStr = txtDir.getText();// 取出使用者輸入的路徑                File file = new File(dirStr);                if (file.isDirectory() && file.exists()) {                    String[] fileNameList = file.list();                    for (String s : fileNameList) {                        txtFileList.append(s + "\r\n");// 別忘了分行符號                    }                } else {                    txtFileList.append("輸入有誤,請重新輸入");                }            }        });    }}

結果:(我讓它顯示我D盤的目錄)

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.