Java写一个动作事件的监听器
时间: 2024-02-13 18:05:10 浏览: 26
可以使用Java中的ActionListener接口来实现动作事件的监听器。以下是一个简单的示例代码:
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ActionListenerExample implements ActionListener {
private JButton button;
public ActionListenerExample() {
JFrame frame = new JFrame("ActionListener Example");
JPanel panel = new JPanel();
button = new JButton("Click me!");
button.addActionListener(this);
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("Button clicked!");
}
}
public static void main(String[] args) {
ActionListenerExample example = new ActionListenerExample();
}
}
```
在这个示例中,我们创建了一个JButton,并将其添加到JPanel中。然后,我们使用addActionListener方法将ActionListenerExample类的实例作为按钮的监听器。当按钮被点击时,actionPerformed方法将被调用,并且我们将在控制台上打印一条消息。