Java學習筆記之SWING — 基本SWING程式(基礎的ActionListener響應)

來源:互聯網
上載者:User

前言:隨著慢慢的深入,發現其實自己什麼都不懂,頓時優越感全失。本來麼,做程式的人要這種優越感做什麼,只會讓你自己走下坡路的,不斷的吸取和理解再嘗試才是生存之道。還是回到基礎的東西來說吧,不然以後又是碰到一大堆的問題。

       關於ActionListener的響應問題,就我的理解可以有兩種方法。第一種就是你放到一個新的類裡面,實現ActionListener介面,然後寫好public void actionPerformed(ActionEvent e)的方法。這種當繼承自JFrame還是蠻有用的,但是如果是一個在public static void main(String[] args)中建立一個JFrame,然後對裡面的(比如按鈕)實現監聽,那麼去實現ActionListener介面就不那麼合適了(哎,很多都是當你做過後才知道什麼是合適的),不過Java提供了另一種解決方案:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class ActionListenerTest ...{
    public static void main(String[] args) ...{
        JFrame frame = new JFrame("Button Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        final JButton jbClose = new JButton("Close the Frame");
        jbClose.addActionListener(new ActionListener () ...{
            public void actionPerformed(ActionEvent e) ...{
                if (e.getSource().equals(jbClose)) ...{
                    System.exit(0);
                }
            }
        }
        );
        
        frame.add(jbClose);
        frame.pack();
        frame.setVisible(true);
    }
}

也就是在addActionListener的參數中新定義到一個ActionListenner並重寫它的actionPerformed。不過要注意的是,這個actionPerformed一定要是public的,不然許可權不夠。還有就是裡面用到的組件在外部必須聲明為final的,這點也許會造成些許使用的限制。

      另一種其實是很常用的那種,前面也用到過,不過這裡再寫一遍好了,翻來翻去很麻煩的。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;public class ButtonFrame extends JFrame implements ActionListener ...{
        JButton jbClose = null;
    public ButtonFrame() ...{
        super("ButtonFrame Test");
        jbClose = new JButton ("Close the Frame in ButtonFrame");
        jbClose.addActionListener(this);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        this.add(jbClose);
        this.pack();
        this.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e) ...{
        if (e.getSource().equals(jbClose)) ...{
            System.exit(0);
        }
    }
    public static void main(String[] args) ...{
        ButtonFrame bf = new ButtonFrame();
    }
}

 

兩個程式的效果是一樣的,都是點擊了按鈕後就結束程式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.