Background color of the selected item in an uneditable JComboBox

前端 未结 3 463
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 00:20

The background color of the selected item in an uneditable JComboBox is a sort of blue:

\"alt

Is

相关标签:
3条回答
  • 2020-12-02 00:58

    The background assigned by the renderer is overriden by the selection background color of the JList that is used in the popup for the combo box. Check out the "paintCurrentValue" method of the BasicComboBoxUI class. So the workaround would be:

    JComboBox comboBox = new JComboBox(...);
    Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
    BasicComboPopup popup = (BasicComboPopup)child;
    JList list = popup.getList();
    list.setSelectionBackground(Color.RED);
    

    This will affect the rendering of the popup as well. If you don't want it to affect the popup then you will need to create a custom renderer to specifically set the background of selected items.

    0 讨论(0)
  • 2020-12-02 00:58

    Have you tried writing your own, custom, ListCellRenderer?

    When that method is asked to provide a cell-rendering component you get the following arguments:

     public Component getListCellRendererComponent(JList list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {
    
    0 讨论(0)
  • 2020-12-02 01:18

    This should work

    jComboBox1.setRenderer(new DefaultListCellRenderer() {
        @Override
        public void paint(Graphics g) {
            setBackground(Color.WHITE);
            setForeground(Color.BLACK);
            super.paint(g);
        }
    });
    
    0 讨论(0)
提交回复
热议问题