首页 > 解决方案 > JComboBox 背景直到悬停在它上面才被绘制

问题描述

我改变了 JComboBox 的背景颜色,但直到你将鼠标悬停在它上面才被绘制。这只是此处演示问题的测试示例。在我的主应用程序中,即使我没有将鼠标悬停在它上面,它也是可见的。在 JFrame 完全加载之前,我看到组合框以白色突出显示了几毫秒,然后变成了预期的颜色。

但我认为这是同一个问题。

在将鼠标悬停在它上面之前:

在此处输入图像描述

悬停在它上面后:

在此处输入图像描述

import javax.swing.*;
import java.awt.*;
import java.util.Arrays;

public class TestComboBox {

    private static final String[] ANIMALS = new String[]{"Cat", "Mouse", "Dog", "Elephant", "Bird", "Goat", "Bear"};
    private static final Color COMBO_COLOR = new Color(71, 81, 93);

    public static class MessageComboBox extends JComboBox<String> {

        public MessageComboBox(DefaultComboBoxModel model) {
            super(model);
            setFont(new Font("Arial", Font.PLAIN, 30));
            setPreferredSize(new Dimension(350, 50));
            setRenderer(new MyRenderer());
        }
    }

    private static class MyRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus) {

            JComponent comp = (JComponent) super.getListCellRendererComponent(list,
                    value, index, isSelected, cellHasFocus);

            list.setBackground(COMBO_COLOR);
            list.setForeground(Color.WHITE);
            list.setOpaque(false);

            return comp;
        }
    }


    public static void main(String[] args) throws Exception {
        String nimbus = Arrays.asList(UIManager.getInstalledLookAndFeels())
                .stream()
                .filter(i -> i.getName().equals("Nimbus"))
                .findFirst()
                .get()
                .getClassName();

        UIManager.setLookAndFeel(nimbus);
        UIManager.put("ComboBox.forceOpaque", false);
        UIManager.put("ComboBox.padding", new Insets(3, 3, 3, 0));

        JFrame jf = new JFrame();
        jf.setSize(800, 400);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);

        MessageComboBox comboBox = new MessageComboBox(new DefaultComboBoxModel(ANIMALS));
        comboBox.setFocusable(true);
        JPanel panel = new JPanel();
        panel.add(comboBox);
        jf.add(panel, BorderLayout.NORTH);
    }
}

任何人都可以帮助解决我在这些屏幕中展示的问题吗?

标签: javaswingjcombobox

解决方案


不要更改里面的列表属性getListCellRendererComponent()。仅更改渲染器本身(实际上是 a Jlabel)。这是正确的方法:

private static class MyRenderer extends DefaultListCellRenderer {
    @Override
    public Component getListCellRendererComponent(JList list, Object value,
                                                  int index, boolean isSelected, boolean cellHasFocus) {

        JLabel comp = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        comp.setBackground(COMBO_COLOR);
        comp.setForeground(Color.WHITE);
        return comp;
    }
}

推荐阅读