Swing and Nimbus: Replace background of JPopupMenu (attached to JMenu)

后端 未结 3 1639
名媛妹妹
名媛妹妹 2021-01-01 20:10

Nimbus often looks great, but for certain color combinations the result is non-optimal. In my case, the background of a JPopupMenu does not fit, which is why I

3条回答
  •  没有蜡笔的小新
    2021-01-01 20:49

    • there are a few mistakes in both answers

    • and above mentioned way to required to override most UIDeafaults that have got impact to the another JComponents and its Color(s)

    • Nimbus has own Painter, one example for that ...

    enter image description here

    from code

    import com.sun.java.swing.Painter;
    import java.awt.*;
    import javax.swing.*;
    
    public class MyPopupWithNimbus {
    
        public MyPopupWithNimbus() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(200, 200);
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            JList list = new JList();
            panel.add(list);
            frame.getContentPane().add(panel);
            JPopupMenu menu = new JPopupMenu();
            menu.add(new JMenuItem("A"));
            menu.add(new JMenuItem("B"));
            menu.add(new JMenuItem("C"));
            JMenu jmenu = new JMenu("D");
            jmenu.add(new JMenuItem("E"));
            menu.add(jmenu);
            frame.setVisible(true);
            menu.show(frame, 50, 50);
        }
    
        public static void main(String[] args) {
    
            try {
                for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(laf.getName())) {
                        UIManager.setLookAndFeel(laf.getClassName());
                        UIManager.getLookAndFeelDefaults().put("PopupMenu[Enabled].backgroundPainter",
                                new FillPainter(new Color(127, 255, 191)));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    MyPopupWithNimbus aa = new MyPopupWithNimbus();
                }
            });
        }
    }
    
    class FillPainter implements Painter {
    
        private final Color color;
    
        FillPainter(Color c) {
            color = c;
        }
    
        @Override
        public void paint(Graphics2D g, JComponent object, int width, int height) {
            g.setColor(color);
            g.fillRect(0, 0, width - 1, height - 1);
        }
    }
    

提交回复
热议问题