import java.awt.*;
public class TestButton {
private Frame f;
protected Button b;
public TestButton() {
f = new Frame("Test");
b = new Button("Press Me!");
b.setActionCommand("ButtonPressed");
}
public void launchFrame() {
b.addActionListener(new ButtonHandler());
f.add(b, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
TestButton guiApp = new TestButton();
guiApp.launchFrame();
}
}
import java.awt.*;
import java.awt.event.*;
public class ButtonHandler extends TestButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==b)
{
System.out.println("Action occurred");
System.out.println("Button's command is: "
+ e.getActionCommand());
}
}
}
我试图在按下按钮 b 但不使用 getSource 时调用 ActionEvent。
最佳答案
你在滥用继承。 ButtonHandler 类不应扩展 TestButton 类,因为处理程序类中的 b 变量引用与显示的完全不同的 Button 对象。我建议:
- 使用 Swing 库,而不是 AWT 库
- 您可以从 ActionEvent 的
getSource()
方法获取按下的 JButton 并直接使用它。 - 如果您需要在处理程序中引用 GUI,请在处理程序的构造函数中传入一个引用。
- 不要滥用继承来解决不涉及继承问题的问题。
例如:
import java.awt.event.ActionEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class TestButton extends JPanel {
private JButton btn = new JButton(new ButtonAction("Press Me!", "ButtonPressed"));
public TestButton() {
add(btn);
}
private static void createAndShowGUI() {
TestButton testButton = new TestButton();
JFrame frame = new JFrame("TestButton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testButton );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
@SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
public ButtonAction(String name, String actionCommand) {
super(name);
putValue(ACTION_COMMAND_KEY, actionCommand);
}
@Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Button's actionCommand is: " + evt.getActionCommand());
}
}
关于按钮上的 Java Actionlistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093092/