问题描述
我更改了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,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);
}
}
解决方法
我不确定,但是我想如果你把这行放在那儿
list.setBackground(COMBO_COLOR);
list.setForeground(Color.WHITE);
list.setOpaque(false);
在此行之前:
JComponent comp = (JComponent) super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
,
请勿更改getListCellRendererComponent()
中的列表属性。仅更改渲染器本身(实际上是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,cellHasFocus);
comp.setBackground(COMBO_COLOR);
comp.setForeground(Color.WHITE);
return comp;
}
}