编程语言
首页 > 编程语言> > 在Java中为TrayIcon更改PopupMenu的LAF

在Java中为TrayIcon更改PopupMenu的LAF

作者:互联网

我有以下代码来创建一个带有PopupMenu的TrayIcon:

public void addToTray()
{
    try 
    {
        try {
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        PopupMenu popMenu= new PopupMenu();
        MenuItem exititem = new MenuItem("Exit");
        popMenu.add(exititem);

        BufferedImage trayImg = ImageIO.read(new File("Geqo.png"));
        ImageIcon ii = new ImageIcon(trayImg);
        TrayIcon trayIcon = new TrayIcon(ii.getImage(), "Geqo", popMenu);
        trayIcon.setImageAutoSize(true);
        SystemTray.getSystemTray().add(trayIcon);
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

此代码用于创建带有PopupMenu的TrayIcon.这很好用.但我不喜欢默认的LAF(Metal,我认为).所以我试图将LAF更改为nimbus,以及操作系统默认值,Windows,但无济于事. LAF似乎没有改变.任何人都可以告诉我如何改变LAF吗?
提前致谢 :)!!

解决方法:

Popup不是Swing组件(因此它不受LookAndFeel管理器的控制).

Popup是一个AWT组件,通常使用本机组件.

相反,你应该尝试更像……

public void addToTray()
{
    try 
    {
        try {
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        BufferedImage trayImg = ImageIO.read(new File("Geqo.png"));
        ImageIcon ii = new ImageIcon(trayImg);
        final TrayIcon trayIcon = new TrayIcon(ii.getImage(), "Geqo", null);

        JPopupMenu jpopup = new JPopupMenu();
        JMenuItem miExit = new JMenuItem("Exit");
        jpopup.add(miExit);

        miExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                SystemTray.getSystemTray().remove(trayIcon);
                System.exit(0);
            }
        });

        trayIcon.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    jpopup.setLocation(e.getX(), e.getY());
                    jpopup.setInvoker(jpopup);
                    jpopup.setVisible(true);
                }
            }
        });

        trayIcon.setImageAutoSize(true);
        SystemTray.getSystemTray().add(trayIcon);
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

这是基于Using JPopupMneu in TrayIcon中提出的想法

…….

标签:java,swing,look-and-feel,trayicon,popupmenu
来源: https://codeday.me/bug/20190629/1326663.html