新聞中心
關(guān)于ActionListener的響應(yīng)問(wèn)題,就我的理解可以有兩種方法。第一種就是你放到一個(gè)新的類里面,實(shí)現(xiàn)Swing ActionListener接口,然后寫好public void actionPerformed(ActionEvent e)的方法。這種當(dāng)繼承自JFrame還是蠻有用的,但是如果是一個(gè)在public static void main(String[] args)中建立一個(gè)JFrame,然后對(duì)里面的(比如按鈕)實(shí)現(xiàn)監(jiān)聽,那么去實(shí)現(xiàn)Swing ActionListener接口就不那么合適了(哎,很多都是當(dāng)你做過(guò)后才知道什么是合適的),不過(guò)Java提供了另一種解決方案:

創(chuàng)新互聯(lián)憑借專業(yè)的設(shè)計(jì)團(tuán)隊(duì)扎實(shí)的技術(shù)支持、優(yōu)質(zhì)高效的服務(wù)意識(shí)和豐厚的資源優(yōu)勢(shì),提供專業(yè)的網(wǎng)站策劃、做網(wǎng)站、成都網(wǎng)站制作、網(wǎng)站優(yōu)化、軟件開發(fā)、網(wǎng)站改版等服務(wù),在成都10余年的網(wǎng)站建設(shè)設(shè)計(jì)經(jīng)驗(yàn),為成都上千余家中小型企業(yè)策劃設(shè)計(jì)了網(wǎng)站。
- 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的參數(shù)中新定義到一個(gè)ActionListenner并重寫它的actionPerformed。不過(guò)要注意的是,這個(gè)actionPerformed一定要是public的,不然權(quán)限不夠。還有就是里面用到的組件在外部必須聲明為final的,這點(diǎn)也許會(huì)造成些許使用的限制。
另一種其實(shí)是很常用的那種,前面也用到過(guò),不過(guò)這里再寫一遍好了,翻來(lái)翻去很麻煩的。
- 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();
- }
- }
兩個(gè)程序的效果是一樣的,都是點(diǎn)擊了按鈕后就結(jié)束程序。 以上是介紹實(shí)現(xiàn)Swing ActionListener接口
當(dāng)前名稱:實(shí)現(xiàn)SwingActionListener接口
文章URL:http://www.fisionsoft.com.cn/article/dphihce.html


咨詢
建站咨詢
