JComboBox-箭头和标签之间的填充/间距 [英] JComboBox - padding / spacing between arrow and label

查看:71
本文介绍了JComboBox-箭头和标签之间的填充/间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created JComboBox and changed it background and foreground color. But I see not expected white-gray vertical line there and I don't know how to fix it. This verticl line should be painted too, but it's not.

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

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

Maybe someone has ideas on how to fix this?

推荐答案

The Nimbus defaults say, the default ComboBox.padding is Insets(3,3,3,3) (See Insets doc). Therefore the unexpected grey line is due to this padding. Since you want to remove the right padding, you can fix your problem by adding this line somewhere to your first UIManager-call:

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

结果:

这篇关于JComboBox-箭头和标签之间的填充/间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆