gpt4 book ai didi

java - JButton ActionListener 没有响应

转载 作者:行者123 更新时间:2023-11-30 08:07:14 25 4
gpt4 key购买 nike

我在网上其他地方找不到答案,所以我来到这里。如果我的代码中的错误非常明显,我提前道歉;我对 java swing 还很陌生。事情是这样的:我创建了一个名为 toggleElevators 的 JButton,我希望它在单击时更改文本。我已经创建了一个 ActionListener 并将其添加到 toggleElevators 中。我现在想要的只是 JButton 在单击时将文本从 Click me 更改为 Clicked

首先,这是 JFrame 执行时的样子:

JFrame

注意:还有第三个类,但它纯粹用于绘制左侧的图片。它与 GridLayout 或 JButton 无关。

Run 类(创建框架并添加 toggleElevators JButton:

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;

import javax.swing.JFrame;

public class Run extends Input{

Input i = new Input();

public static void main(String[] args) {
new Run();
}

public Run() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Elevators");
frame.setLayout(new GridLayout(0, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Elevators(Color.MAGENTA, true));
frame.add(new Elevators(Color.ORANGE, false));
frame.setSize(800,600);
frame.setResizable(false);

frame.getContentPane().add(toggleElevators); //adds toggleElevators button to JFrame
i.addButtonListeners(); //calls method defined in Input class, which adds the ActionListener to the toggleElevators button

frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

}

Input 类(创建 toggleElevators JButton 及其 ActionListener):

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

public class Input {
JButton toggleElevators = new JButton("Click me.");

public void addButtonListeners() {
toggleElevators.addActionListener(new toggleElevatorsListener());
}

class toggleElevatorsListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
toggleElevators.setText("Clicked.");
System.out.println("ActionListener called."); //I know the ActionListener is not being called because this line is not being printed out in the console
}
}
}

最佳答案

您的 Run 类扩展了输入,但也有一个名为 i 的输入。您将 this.toggleElevators 添加到框架,但将监听器添加到 i.toggleElevators

从类中删除 i 字段。我也会完全忘记定义和扩展输入类。它没有任何目的,而且似乎只会让你困惑而不是帮助你。

关于java - JButton ActionListener 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30927164/

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