程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Swing中的ActionListener響應研究

Swing中的ActionListener響應研究

編輯:關於JAVA

關於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();
  }
}

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved