Java中如何使用系统托盘

时间:2021-10-09 03:36:19
代码如下:
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class SystemTrayDemo extends JFrame {

// 定义加载的图片资源
public static final Image image = Toolkit.getDefaultToolkit()
.getImage("src/images/snake.jpg");
// 定义窗口大小
public static final int GAME_WIDTH = 500;
public static final int GAME_HEIGHT = 500;
// 获取屏幕窗口大小
public static final int WIDTH = Toolkit.getDefaultToolkit()
.getScreenSize().width;
public static final int HEIGHT = Toolkit.getDefaultToolkit()
.getScreenSize().height;

// 构造函数
public SystemTrayDemo() {

// 设置游戏标题
this.setTitle("系统托盘");
// 设置窗口图标
this.setIconImage(image);
// 设置窗口初始位置
this.setLocation((WIDTH - GAME_WIDTH) / 2, (HEIGHT - GAME_HEIGHT) / 2);
// 设置窗口大小
this.setSize(GAME_WIDTH, GAME_HEIGHT);

// 判断当前平台是否支持系统托盘
if (SystemTray.isSupported()) {
// 获取系统托盘
SystemTray tray = SystemTray.getSystemTray();

// 创建弹出菜单
PopupMenu popup = new PopupMenu();
MenuItem item1 = new MenuItem("显示主界面");
MenuItem item2 = new MenuItem("退出程序");
popup.add(item1);
popup.add(item2);

// 显示主界面
item1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(true);
}
});
// 退出程序
item2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// 创建系统图标
TrayIcon trayIcon = new TrayIcon(image, "系统托盘", popup);
try {
//在系统托盘添加图标
tray.add(trayIcon);
} catch (Exception e) {
e.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(this, "无法使用系统托盘!");
}

// 设置窗口大小不可改变
this.setResizable(false);
// 设置窗口显示
this.setVisible(true);

}

public static void main(String[] args) {
new SystemTrayDemo();
}

}