请用Java写符合以下要求的代码,并用中文回答 Write a simple GUI program with a button that responds to events from a mouse being pressed and released. The button should display: • the message “No action” when no action is taken on the mouse. • the message “Pressing down” when the mouse is pressed.
时间: 2023-11-22 21:54:34 浏览: 61
基于JAVA的鼠标事件处理
以下是一个简单的Java GUI程序,包含一个按钮和一个标签。当鼠标按下按钮时,标签将显示“Pressing down”,当鼠标释放按钮时,标签将显示“No action”。
```java
import javax.swing.*;
import java.awt.event.*;
public class MouseButtonGUI extends JFrame implements MouseListener {
private JButton button;
private JLabel label;
public MouseButtonGUI() {
setTitle("Mouse Button GUI");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Click me!");
button.addMouseListener(this);
label = new JLabel("No action");
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new MouseButtonGUI();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Pressing down");
}
@Override
public void mouseReleased(MouseEvent e) {
label.setText("No action");
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
```
阅读全文