【问题标题】:JComboBox - padding / spacing between arrow and labelJComboBox - 箭头和标签之间的填充/间距
【发布时间】:2020-10-28 18:08:41
【问题描述】:

我创建了 JComboBox 并更改了它的背景和前景色。但我在那里没有看到预期的白灰色垂直线,我不知道如何修复它。这条垂直线也应该画,但不是。

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

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

【问题讨论】:

    标签: java swing jcombobox nimbus


    【解决方案1】:

    Nimbus defaults 说,默认的ComboBox.paddingInsets(3,3,3,3)(参见Insets doc)。因此,意外的灰线是由于此填充造成的。由于您想删除正确的填充,您可以通过将此行添加到您的第一个 UIManager-call 的某处来解决您的问题:

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

    结果:

    【讨论】:

    • 非常感谢 Moritz,现在我明白它是如何工作的了。
    • 您对组合框颜色的问题:您可能还想为此打开另一个问题。我无法解决这个问题。
    • 是的,我想我会的。这只是此处演示问题的测试示例。你知道,在我的主应用程序中,即使我不悬停它也是可见的。但在 JFrame 完全加载之前,我看到组合框以白色突出显示几毫秒,然后被涂上预期的颜色。我不知道如何实际展示它。因为我应该把我所有的代码都贴在这里,但它太多了..
    • 这应该没问题,因为您的问题可以通过剪断这段代码重现。
    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2022-01-18
    • 2011-08-22
    • 1970-01-01
    • 2021-05-13
    相关资源
    最近更新 更多