I want to create a JFrame
instance and on the click of its minimize button
, I would like to hide it to the System Tray
which is usually the taskbar
of windows.
I'd come to know that by using SystemTray
class in java.awt
package I can do so but neither I'm getting any tutorial on it nor any working program example.
I'd asked this question here to either get the link to tutorial site for SystemTray
class or if any body knows how to trap the window minimizing event, a working example.
The WindowListener
interface and JFrame
's addWindowListener()
method should help you determine when the frame has been minimised.
This will trap the window minimized event and will create a tray icon. It will also remove the window from the taskbar and it will add a listener on the tray icon so that a mouseclick would restore the window. The code is a bit scrappy but should be good enough for your learning purposes:
public class Qwe extends JFrame {
public static void main(String[] args) {
final Qwe qwe = new Qwe();
qwe.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == ICONIFIED) {
try {
final TrayIcon trayIcon = new TrayIcon(new ImageIcon("/usr/share/icons/gnome/16x16/emotes/face-plain.png").getImage());
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
qwe.setVisible(true);
SystemTray.getSystemTray().remove(trayIcon);
}
});
SystemTray.getSystemTray().add(trayIcon);
qwe.setVisible(false);
} catch (AWTException e1) {
e1.printStackTrace();
}
}
}
});
qwe.setSize(200, 200);
qwe.setVisible(true);
}
}
best way would be create follows
1) SystemTray
2) add JPopopMenu
to the SystemTray's Icon
3) set DefaultCloseOperation
for TopLevelContainer (in your case JFrame)
by using WindowListener setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
in other cases always works setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
notice don't forget declare System.exit(1)
to the SystemTray's JpopupMenu
, from JMenuItem
or another Action/Event
, because in this form currenet JVM never gone from Native OS until PC power-off or restart
private void windowStateChanged(java.awt.event.WindowEvent evt) {
// Use getExtendedstate here.
}
WindowStateListener
docsFrame.getExtendedState()
docsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With