java - 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);
}
}
任何人都可以帮助解决我在这些屏幕中展示的问题吗?
解决方案
不要更改里面的列表属性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;
}
}
推荐阅读
- javascript - AddListener 工作,但 RemoveListener 不能正常工作
- python - 如何在 jupyter notebook 中更改我的 python 版本?
- arrays - 过滤调用重复颤动
- python - 使用 numpy 的线性和非线性系统的雅可比行列式
- json - 我的 Conditional0 JSON 语句未按预期工作
- mongodb - Spring Data Mongo Db 使用 @DBRef 从返回 null 的某个集合中获取值
- json - 如何通过在 Flutter 中以 JSON_Serializable 方式遍历 JSON 数组来填充 GridView?
- matlab - for循环中的索引问题?位置 2 中的索引超出数组边界(不得超过 27630)。MATLAB
- google-cloud-storage - 通过 Google 实例的公共 url 从存储桶下载对象是否收费?
- python - 在 Matplotlib 中绘制带有图例的数据框线图