问题描述
目标是在主方法中使用LookAndFeel时更改所有组合框的背景。 但是当LookAndFeel存在和不存在时,我得到的结果都是不同的。
没有LookAndFeel:调整JFrame大小后,JComboBox可见
import javax.swing.*;
import java.awt.*;
import static java.awt.Color.WHITE;
public class TestFrame extends JFrame {
private static final String[] ANIMALS = new String[]{"Cat","Mouse","Dog","Elephant","Bird","Goat","Bear"};
public TestFrame() {
setSize(600,300);
setVisible(true);
setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JComboBox<String> comboBox = new JComboBox<>();
comboBox.setModel(new DefaultComboBoxModel<>(ANIMALS));
comboBox.setForeground(WHITE);
comboBox.setBackground(new Color(71,81,93));
comboBox.getEditor().getEditorComponent().setBackground(new Color(71,93));
comboBox.getEditor().getEditorComponent().setForeground(WHITE);
comboBox.setRenderer(new DefaultListCellRenderer() {
@Override
public void paint(Graphics g) {
setBackground(new Color(71,93));
setForeground(WHITE);
super.paint(g);
}
});
panel.add(comboBox);
add(panel);
}
public static void main(String[] args) {
new TestFrame();
}
}
使用LookAndFeel:
import javax.swing.*;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.awt.Color.WHITE;
public class TestFrame extends JFrame {
private static final String[] ANIMALS = new String[]{"Cat",93));
setForeground(WHITE);
super.paint(g);
}
});
panel.add(comboBox);
add(panel);
}
public static void main(String[] args) {
try {
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | illegalaccessexception | UnsupportedLookAndFeelException ex) {
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE,null,ex);
}
/* Create and display the form */
EventQueue.invokelater(new Runnable() {
public void run() {
new TestFrame();
}
});
}
}
在启用LookAndFeel的情况下如何实现组合框的完整绘制?
解决方法
没有禁用或启用LookAndFeel
之类的东西。应用程序中始终会设置外观。您似乎只是设置了另一个LookAndFeel
,在您的情况下为 Nimbus 。但是,为回答您的问题,雨云将DefaultListCellRenderer
的不透明度属性设置为false
,(例如,MetalLookAndFeel
将其设置为true
),这就是您显示视觉效果的原因。您应该可以通过覆盖getListCellRendererComponent
的{{1}}方法来解决此问题,如下所示:
DefaultListCellRenderer
您还必须将UIManagers属性@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;
}
设置为ComboBox.forceOpaque
,如下所示:
false
可以找到here的 Nimubs defauts的完整列表。
如有需要,可提供已解决问题的完整示例:
UIManager.put("ComboBox.forceOpaque",false);
导致:
顺便说一句,我通过使用 NetBeans IDE 的可视调试器解决了这一问题。