事件处理器的问题

SilentHunter460 SilentHunter460 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
button1.addActionListener(new button1click()); 这句话只是实例化一个button1click对象,虽然它的类里边有public void actionPerformed(ActionEvent arg0)方法,但代码里没有一句话是调用这个方法,更没有传入ActionEvent对象类型的参数,为什么单击button1的时候会执行这个方法?


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class test {

public static void main(String[] args) {
JFrame window1 = newwindow(400, 300, "window1");
JButton button1 = newbutton(110, 35, "button1");
window1.add(button1);
button1.addActionListener(new button1click());
}

public static JFrame newwindow(int width, int height, String title) {
JFrame theframe = new JFrame(title);
theframe.setSize(width, height);
theframe.setLayout(new FlowLayout());
theframe.setVisible(true);
theframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return theframe;
}

public static JButton newbutton(int width, int height, String title) {
JButton thebutton = new JButton(title);
thebutton.setPreferredSize(new Dimension(width, height));
return thebutton;
}
}

class button1click implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(arg0.getActionCommand());
}
}
...全文
评论 8
收藏 已收藏
分享
返回顶部
SilentHunter460
Java SE 62,621 成员 307,251 内容