java - JComboBox - 箭头和标签之间的填充/间距
问题描述
我创建了 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);
}
}
也许有人对如何解决这个问题有想法?
解决方案
Nimbus 默认值说,默认值是ComboBox.padding
(Insets(3,3,3,3)
参见插图文档)。因此,意外的灰线是由于此填充造成的。由于您想删除正确的填充,您可以通过将此行添加到您的第一个UIManager
-call 的某处来解决您的问题:
UIManager.put("ComboBox.padding", new Insets(3, 3, 3, 0));
推荐阅读
- ios - 使用协议对视图模型实施限制-AssociatedType/conditional-conformance/swift
- python - 多个 Python 安装;导入 scipy 失败,出现 WinError 193
- excel - Excel VBA 宏代码返回错误 424 和 1004
- paypal - PayPal 智能支付按钮 - 替代支付方式 - 400 错误请求
- php - PHP 与 Kafka - rdkafka
- json - 如何使用 json api 请求重新启动 Heroku dynos
- r - 将选择范围重新调整为 0 - 1?
- react-native - 如何将 pdf 从 api 响应中保存到文件系统中反应原生?
- javascript - 根据用户位置从 openweather api 获取数据
- qpdf - 如何将 pdf 文件合并在一起并只从每个文件中获取第一页?