How to implement system tray function in Java.
Example diagram
Project package structure diagram
Screenshot of system operation
Applying the core logic description, hiding to the tray essentially means hiding the form. That is, setVisible(false), and displaying the form means setVisible(true).
The project code is as follows:
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MainFrame extends JFrame implements ActionListener{
private static final long serialVersionUID = -7078030311369039390L;
private JMenu menu;
private JMenuBar jmenuBar;
private String [] jmItemName = {"Place in tray","System exit"};
public MainFrame(){
super("phone book");
init();
this.setSize(500,400);
this.setJMenuBar(jmenuBar);
this.setLocationRelativeTo(null);
systemTray(); //system tray
}
/**
* Initialization interface
*/
public void init(){
menu = new JMenu("System Form");
for(int i=0; i<jmItemName.length; i++){
JMenuItem menuItem = new JMenuItem(jmItemName[i]);
menuItem.addActionListener(this);
menu.add(menuItem);
}
this.jmenuBar = new JMenuBar();
this.jmenuBar.add(menu);
}
@Override
public void actionPerformed(ActionEvent e) {
String actions = e.getActionCommand();
if("Place on tray".equals(actions)){
this.setVisible(false);
}
if("System exit".equals(actions)){
System.exit(0);
}
}
/**System tray icon processing.*/
private void systemTray(){
if(SystemTray.isSupported()){ //Determine whether the system supports the tray function.
URL resource = this.getClass().getResource("systray.jpg"); //Get the image path
ImageIcon icon = new ImageIcon(resource); //Create image object
PopupMenu popupMenu = new PopupMenu(); //Create a popup menu object
MenuItem itemExit = new MenuItem("Exit the system"); //Create the exit item in the pop-up menu
MenuItem itemShow = new MenuItem("Display form"); //Create a display main form item in the pop-up menu.
itemExit.addActionListener(new ActionListener() { //Add an event listener to the exit image
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
itemShow.addActionListener(new ActionListener() { //Add an event listener to minimize the form.
@Override
public void actionPerformed(ActionEvent e) {
setVisible(true);
}
});
popupMenu.add(itemExit);
popupMenu.add(itemShow);
TrayIcon trayIcon = new TrayIcon(icon.getImage(),"Phonebook System",popupMenu);
SystemTray sysTray = SystemTray.getSystemTray();
try {
sysTray.add(trayIcon);
} catch (AWTException e1) { }
}
}
/**
* Main method
* @param args
*/
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
}