【发布时间】:2014-07-23 13:34:31
【问题描述】:
我想将现有 jcombobox(已添加项目)中的一个选择项更改为斜体?有什么办法吗?
【问题讨论】:
-
JComboBox的元素渲染是通过ListCellRenderer控制的。更多详情请关注Providing a Custom Renderer
我想将现有 jcombobox(已添加项目)中的一个选择项更改为斜体?有什么办法吗?
【问题讨论】:
JComboBox 的元素渲染是通过ListCellRenderer 控制的。更多详情请关注Providing a Custom Renderer
希望这篇文章能帮到你:)
您只需将 ListCellRenderer 添加到您的 ComboBox。
class MyComboBoxRenderer extends JLabel
implements ListCellRenderer {
. . .
public ComboBoxRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String pet = petStrings[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(pet);
setFont(list.getFont()); //HERE YOU ALSO HAVE TO SET THE COLOR OR SOMETHING LIKE THAT
} else {
setUhOhText(pet + " (no image available)",
list.getFont());
}
return this;
}
. . .
}
【讨论】: