🌺① 监听按钮点击事件
🌺② 监听鼠标事件
🌺③ 监听文本框事件
🌺④ 监听列表事件
① 监听按钮点击事件
下面的代码演示了如何监听按钮的点击事件,并在点击时弹出一个对话框。
import javax.swing.*;
import java.awt.event.*;
public class ButtonDemo {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "You clicked the button!");
}
});
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
在这个例子中,我们创建了一个JFrame窗口和一个JButton按钮,并向按钮注册了一个ActionListener监听器。当用户点击按钮时,ActionListener的actionPerformed方法会被调用,弹出一个对话框,提示用户已经点击了按钮。
🌺详细介绍
🌺