Search code examples
javaswingjmenujmenuitem

Java setPressedIcon not working


I have menu in my application, and I want to set menu item normal state icon, and pressed state icon. Normal state icon is added, but when I press menu item, normal state icon is not changed by pressed state icon. What is problem here:

        JMenu m=new JMenu(text);
        m.setBackground(getTheme().colors.menuColor());
        m.setOpaque(false);
        m.setIcon(core.getIcon(text, "normal"));
        m.setPressedIcon(core.getIcon("webmaps", "pressed"));

Solution

  • This issue has been seen before. The inherited setPressedIcon does not change the background Icon on the the JMenu (or indeed JMenuItem). You could use a MenuListener on the component as a workaround:

    m.addMenuListener(new MenuListener() {
    
        @Override
        public void menuSelected(MenuEvent e) {
            JMenu menu = (JMenu) e.getSource();
            menu.setIcon(core.getIcon("webmaps", "pressed"));
        }
    
        @Override
        public void menuDeselected(MenuEvent e) {
            JMenu menu = (JMenu) e.getSource();
            menu.setIcon(core.getIcon(text, "normal"));
        }
    
        @Override
        public void menuCanceled(MenuEvent e) {
            JMenu menu = (JMenu) e.getSource();
            menu.setIcon(core.getIcon(text, "normal"));
        }
    });