gpt4 book ai didi

java - 我需要一些指导来理解 ActionListener 和 actionPerformed(ActionEvent) 是如何工作的

转载 作者:行者123 更新时间:2023-12-04 05:01:26 24 4
gpt4 key购买 nike

我正在自学 Java 的 Swing 组件,但遇到了一些概念上的障碍。我确信我弄错了一些特定的术语,但希望我能很好地传达我的困难以获得一两个答案。

我有以下代码,为简洁起见,已删除:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//
public class CreateButtonSel {
public static void main(String[] args) {
ButtonSel thisButtonSel = new ButtonSel();
final int WIDTH = 250;
final int HEIGHT = 250;
thisButtonSel.setSize(WIDTH,HEIGHT);
thisButtonSel.setVisible(true);
}
}

当我添加 implements ActionListener (在下面注释掉)我收到一个错误 ButtonSel is not abstract and does not override abstract method actionPerformed(ActionEvent) .从我在 javadocs 和各种网站上读到的内容来看,我认为该错误是由于尚未在方法中定义操作造成的。类似的东西
public void actionPerformed(ActionEvent clickButton) {
do stuff;
{

但是,我不清楚该方法需要在哪里使用。我猜它住在 ButtonSel类与构造函数——因为那是我定义按钮对象的地方。但是,我也可以将其视为 CreateButtonSel 中的一种方法类,并传递给 ButtonSel作为参数。那么,问题是如何或是否将这些按钮 Action 特征传递给构造函数?或者,如果它们在 CreateButtonSel 中,它们是否会自动附加到由构造函数创建的按钮对象中?课?

有人可以解释一下程序流程应该如何工作以及什么时候调用哪个方法吗?
//    public class ButtonSel extends JFrame implements ActionListener {
public class ButtonSel extends JFrame {
JButton approveButton = new JButton("Go");
JPanel buttonPanel = new JPanel();
//
public ButtonSel() {
super("ButtonTest");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(approveButton);
}
}

最佳答案

How to Write an ActionListener举个例子。您还可以在论坛中搜索其他工作示例。

关于java - 我需要一些指导来理解 ActionListener 和 actionPerformed(ActionEvent) 是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16111113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com