JComboBox-箭头和标签之间的填充/间距

问题描述

我创建了JComboBox并将其更改为背景和前景色。但是我看不到那里有预期的白灰色垂直线,而且我不知道如何解决。此垂直线也应绘制,但不是。

enter image description here

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);

        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));
        JPanel panel = new JPanel();
        panel.add(comboBox);
        jf.add(panel,BorderLayout.norTH);
    }
}

也许有人对如何解决这个问题有想法?

解决方法

Nimbus defaults说,默认ComboBox.paddingInsets(3,3,3)(请参阅Insets doc)。因此,意外的灰线归因于此填充。由于您要删除正确的填充,因此可以通过在您的第一个UIManager呼叫中的某处添加以下行来解决问题:

UIManager.put("ComboBox.padding",new Insets(3,0));

结果: enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...