JComboBox:将一个选择项更改为斜体

时间:2014-07-23 04:07:15

标签: java swing jcombobox

我想将现有 jcombobox(项目已添加)中的一个选项更改为斜体?有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

我希望这个可以帮助你:)

您只需将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;
}
. . .

}

相关问题