Неожиданное изменение фона заголовка custom jcombobox в процессе - PullRequest
1 голос
/ 01 августа 2020
• 1000 1005 * когда я выбираю элемент в раскрывающемся списке, цвет заголовка неожиданно меняется на цвет компонента по умолчанию.
public class MyComboBoxRenderer extends JLabel implements ListCellRenderer<Object> {
    private String _title;
    private JButton header;
    public MyComboBoxRenderer(String title) {
        _title = title;
    }

    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value,
            int index, boolean isSelected, boolean hasFocus) {
        JButton item = new JButton();
        item.setOpaque(true);
        item.setBorderPainted(false);
        item.setFocusPainted(false);
        item.setBackground(isSelected ? Frame.LIGHTER_COLOR : Frame.LIGHT_COLOR ); 
        ImageIcon dot = new ImageIcon("image/icon/orange_dot.png");
        if (index == -1){
            item.setText(_title);
            header=item;
            return item; 
        }
        else{
            item.setIcon(dot);
            item.setIconTextGap(30);
            item.setText(value.toString());
            return item;
        }
        
    }
    
    public JButton getHeader(){
        return header;
    }
}
public static class MyComboBoxUI extends BasicComboBoxUI {
        final JButton button= new JButton(EXPAND_ARROW);
        protected void installDefaults() {
            super.installDefaults();
        }

        @Override
        protected JButton createArrowButton() {
            button.setContentAreaFilled(false);
            button.setBorder(null);
            return button;
        }

        @Override
        public void configureArrowButton() {
            super.configureArrowButton();
        }
        
        public JButton getArrowButton(){
            return button;
        }
    }
public class ComboBox extends JComboBox{
    public boolean isExpanded = false;
    private MyComboBoxRenderer renderer;
    public ComboBox(){
        super();
        this.setUI(new MyComboBoxUI());
    }
    public ComboBox(String[] list){
        super(list);
        renderer = new MyComboBoxRenderer("Lists Of Vocab");
        this.setUI(new MyComboBoxUI());
        this.setFont(Frame.I_FONT);
        this.setForeground(Frame.FONT_COLOR);
        this.setBackground(Frame.LIGHT_COLOR);
        this.setRenderer(renderer);
        MyComboBoxUI ui = (MyComboBoxUI) this.getUI();
        JButton arrowButton = ui.getArrowButton();
        arrowButton.addActionListener((ActionEvent e)->{
            isExpanded = !isExpanded;
            if(isExpanded == true){
                arrowButton.setIcon(COLLAPSE_ARROW);
            }
            else{
                arrowButton.setIcon(EXPAND_ARROW);
            }
        });
    }
    public MyComboBoxRenderer getRenderer(){
        return renderer;
    }

Я добавляю это поле со списком в боковую панель

    private void addCheckBoxToSideBar(){
        ComboBox lists = new ComboBox(listNames);
        lists.setAlignmentX(Component.LEFT_ALIGNMENT); // have to have
        lists.addItemListener(new ItemListener(){
            @Override
            public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                CardLayout cl = (CardLayout)(mainPane.getLayout());
                cl.show(mainPane, (String)e.getItem());[enter image description here][1]
            }
        }
    });

        sideBar.add(lists);
    }

Это первое:

https://i.stack.imgur.com/ctVnT.png

Но когда я нажимаю, чтобы выбрать элемент, он меняет цвет на цвет по умолчанию:

https://i.stack.imgur.com/KkhhO.png

Это то, что я пробовал, но они не работали:

  • , чтобы установить фон заголовка в itemStateChanged
  • получить его JTextfield из BasicComboBoxEditor

Интересно, вызывает ли обновление пользовательского интерфейса эту проблему, но я не очень разбираюсь в этом.

1 Ответ

0 голосов
/ 01 августа 2020

В вашем MyComboBoxUI попробуйте переопределить этот метод:

@Override
public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus)
{
 Color t = g.getColor();
 g.setColor(your_color);
 g.fillRect(bounds.x,bounds.y,bounds.width,bounds.height);
 g.setColor(t);
}
...