java swing action_Swing ActionListener接口

处理ActionEvent的类应该实现此接口。该类的对象必须在组件中注册。可以使用addActionListener()方法注册该对象。当动作事件发生时,将调用该对象的actionPerformed方法。

接口声明

以下是java.awt.event.ActionListener接口的声明 -

public interface ActionListener

extends EventListener

接口方法编号

方法

描述

1

void actionPerformed(ActionEvent e)

发生操作时调用。

方法继承

此接口从以下接口继承方法 -

java.awt.EventListener

ActionListener示例

使用编辑器创建以下Java程序:ActionListenerExample.java

package com.yiibai.swing.listener;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class ActionListenerExample {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

public ActionListenerExample() {

prepareGUI();

}

public static void main(String[] args) {

ActionListenerExample swingListenerDemo = new ActionListenerExample();

swingListenerDemo.showActionListenerDemo();

}

private void prepareGUI() {

// from http://www.yiibai.com/swing/

mainFrame = new JFrame("Java SWING ActionListener示例");

mainFrame.setSize(400, 400);

mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel("", JLabel.CENTER);

statusLabel = new JLabel("", JLabel.CENTER);

statusLabel.setSize(350, 100);

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent) {

System.exit(0);

}

});

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

}

private void showActionListenerDemo() {

headerLabel.setText("Listener in action: ActionListener");

JPanel panel = new JPanel();

panel.setBackground(Color.ORANGE);

JButton okButton = new JButton("确定");

okButton.addActionListener(new CustomActionListener());

panel.add(okButton);

controlPanel.add(panel);

mainFrame.setVisible(true);

}

class CustomActionListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

statusLabel.setText("点击了'确定'按钮");

}

}

}

执行上面示例代码,得到以下结果:

4128a984efdd1a1959df25a7339f8eba.png

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值