Java swing 窗口最小化到任务栏 点击右键显示菜单(复制代码即可运行查看效果)...
时间: 2023-12-24 20:05:04 浏览: 119
以下是Java Swing实现窗口最小化到任务栏并右键显示菜单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MinimizeToTaskbar extends JFrame {
private JPopupMenu popupMenu;
public MinimizeToTaskbar() {
super("Minimize To Taskbar");
// 创建一个弹出菜单
popupMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("退出");
menuItem.addActionListener(e -> System.exit(0));
popupMenu.add(menuItem);
// 窗口最小化到任务栏
addWindowStateListener(e -> {
if ((e.getNewState() & Frame.ICONIFIED) == Frame.ICONIFIED) {
setVisible(false);
}
});
// 鼠标右键显示菜单
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MinimizeToTaskbar();
}
}
```
运行后,窗口可以被最小化到任务栏,右键点击窗口时会显示一个菜单。注意,在Windows系统下,需要设置JFrame的默认关闭操作为`JFrame.EXIT_ON_CLOSE`,否则窗口关闭后程序不会退出。
阅读全文