gpt4 book ai didi

java - 在单击交叉而不是最小化按钮的情况下在系统托盘中添加 jframe

转载 作者:行者123 更新时间:2023-11-30 08:58:56 26 4
gpt4 key购买 nike

frame.addWindowStateListener(new WindowStateListener() {

@Override
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == ICONIFIED) {
try {
tray.add(trayIcon);
frameLogin.setVisible(false);
} catch (AWTException ex) {
}
}
}

});

这会将我的应用程序添加到系统托盘中,但我想在用户单击交叉时将我的应用程序添加到系统托盘中,而不是在最小化的情况下

最佳答案

正如@mKorbel 所说,WindowListener + DefaultCloseOperation 对我来说效果很好:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public final class SystemTrayTest {
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setResizable(false);
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

if (!SystemTray.isSupported()) {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return;
}
final SystemTray tray = SystemTray.getSystemTray();
BufferedImage i= new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = i.createGraphics();
g.setColor(Color.RED);
g.fillRect(2, 2, 12, 12);
g.dispose();
final PopupMenu popup = new PopupMenu();
final TrayIcon icon = new TrayIcon(i, "TRAY", popup);

Handler h = new Handler(tray, icon);
frame.addWindowStateListener(h);
frame.addWindowListener(h);

MenuItem item1 = new MenuItem("OPEN");
item1.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
tray.remove(icon);
}
});
MenuItem item2 = new MenuItem("EXIT");
item2.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
tray.remove(icon);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.dispose();
//System.exit(0);
}
});
popup.add(item1);
popup.add(item2);
}
}

class Handler extends WindowAdapter {
private final SystemTray tray;
private final TrayIcon icon;
public Handler(SystemTray tray, TrayIcon icon) {
super();
this.tray = tray;
this.icon = icon;
}
private void addTrayIconDisposeFrame(JFrame frame) {
try {
tray.add(icon);
frame.dispose();
//frame.setVisible(false);
} catch (AWTException ex) {
ex.printStackTrace();
}
}
@Override public void windowStateChanged(WindowEvent e) {
System.out.println("ICONIFIED");
if (e.getNewState() == Frame.ICONIFIED) {
addTrayIconDisposeFrame((JFrame) e.getSource());
}
}
@Override public void windowClosing(WindowEvent e) {
System.out.println("windowClosing");
addTrayIconDisposeFrame((JFrame) e.getSource());
}
}

关于java - 在单击交叉而不是最小化按钮的情况下在系统托盘中添加 jframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27442164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com