java中按钮监听以及鼠标监听的使用
时间: 2024-03-17 07:47:12 浏览: 61
Java中的按钮监听和鼠标监听可以通过实现ActionListener和MouseListener接口来实现。
按钮监听使用示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonListenerExample implements ActionListener {
private JFrame frame;
private JButton button;
public ButtonListenerExample() {
frame = new JFrame("Button Listener Example");
button = new JButton("Click me!");
// 添加按钮监听器
button.addActionListener(this);
frame.setLayout(new FlowLayout());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("Button clicked!");
}
}
public static void main(String[] args) {
new ButtonListenerExample();
}
}
```
鼠标监听使用示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseListenerExample implements MouseListener {
private JFrame frame;
private JPanel panel;
public MouseListenerExample() {
frame = new JFrame("Mouse Listener Example");
panel = new JPanel();
// 添加鼠标监听器
panel.addMouseListener(this);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered!");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited!");
}
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed!");
}
public void mouseReleased(MouseEvent e) {
System.out.println("Mouse released!");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
```
阅读全文