【发布时间】:2015-06-18 22:54:27
【问题描述】:
我在网上其他任何地方都找不到答案,所以我来到了这里。如果我的代码中的错误非常明显,我提前道歉;我对 java swing 还是很陌生。这是发生了什么:我创建了一个名为toggleElevators 的JButton,我希望它在单击时更改文本。我已经创建了一个 ActionListener 并将其添加到 toggleElevators。我现在只想让 JButton 在单击时将文本从 Click me 更改为 Clicked。
首先,这是 JFrame 在执行时的样子:
注意:还有第三类,但它纯粹用于绘制左边的图片。它与 GridLayout 或 JButton 无关。
Run 类(创建框架并添加toggleElevatorsJButton:
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
}
}
}
【问题讨论】:
-
你为什么要把事情复杂化?为什么不直接在
JButton中添加ActionListener? -
@NabeelOmer 这是导致问题的原因吗?为 ActionListener 创建了一个内部类?我不认为那会做任何事情。
-
我现在不在电脑附近(见鬼,这里是凌晨 4 点),但是您通过为
ActionListener创建单独的类来使事情复杂化,尝试将其添加到JButton直接地。还有 -
我认为这就是为什么匿名类或 lambda 函数适用于 ¿?