java按钮大小改变事件_Java语言系列——Swing中Button事件监听

一、前言

今天在使用Java Swing中的JButton的事件触发机制时遇到了许多问题,简单的了解了一下。

二、事件监听机制

下面用一张图分析事件监听的机制(图片来自网络):

fa56325c3113694e820d1279af9e2283.png

三、代码分析

3.1 分析一

1.事件源注册监听器

JButton newButton = new JButton();

newButton.addActionLister(listener);

1

2

JButtonnewButton=newJButton();

newButton.addActionLister(listener);

2.用户触发事件

例如单击该按钮

3.创建事件对象即ActionEvent Object

ActionEvent e;

1

ActionEvente;

4.将事件的对象传递给监听器并调用监听器方法

@Override

public void actionPerformed(ActionEvent e) {

// 相应的逻辑判断

if(e.getSource()==jb)

{

this.dispose();

// 点击按钮时frame1销毁,new一个frame2

new frame2();

}

}

1

2

3

4

5

6

7

8

9

10

@Override

publicvoidactionPerformed(ActionEvente){

// 相应的逻辑判断

if(e.getSource()==jb)

{

this.dispose();

// 点击按钮时frame1销毁,new一个frame2

newframe2();

}

}

3.2 分析二

以上代码也可以这样设计:

JButton newButton = new JButton();

newButton.addActionLister(listener);

newButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

if(e.getSource()==jb)

{

this.dispose();

// 点击按钮时frame1销毁,new一个frame2

new frame2();

}

});

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

JButtonnewButton=newJButton();

newButton.addActionLister(listener);

newButton.addActionListener(newActionListener(){

@Override

publicvoidactionPerformed(ActionEvente){

if(e.getSource()==jb)

{

this.dispose();

// 点击按钮时frame1销毁,new一个frame2

newframe2();

}

});

}

四、代码实现

public static void main(String[] args) {

JFrame jf = new JFrame("事件监听测试");

jf.setVisible(true);

jf.setSize(100, 200);

JButton jb = new JButton("触发事件");

jf.add(jb);

jb.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// 进行逻辑处理即可

System.out.println("触发了事件");

}

});

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

publicstaticvoidmain(String[]args){

JFramejf=newJFrame("事件监听测试");

jf.setVisible(true);

jf.setSize(100,200);

JButtonjb=newJButton("触发事件");

jf.add(jb);

jb.addActionListener(newActionListener(){

@Override

publicvoidactionPerformed(ActionEvente){

// 进行逻辑处理即可

System.out.println("触发了事件");

}

});

}

五、详解actionListener()和actionPerformed()

5.1 actionListener()

actionListener()接口是Java中关于事件处理的一个接口,继承自EventListener。

5.2 actionPerformed()

actionPerformed()是actionListener()接口中声明的一个方法,在监听器接收到触发事件源时自动调用的,比如按下按钮后,它和KeyListener,MouseLisenter,WindowListener等是同一性质的方法(分别对应键盘监听、鼠标监听、窗口监听)。在这个方法中可以做相应的逻辑处理。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值