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

Java JComboBox:将一个选择项更改为斜体,java,swing,jcombobox,Java,Swing,Jcombobox,我想将现有的jcombobox中的一个选择项(已添加项)更改为斜体?有什么方法可以做到这一点吗?我希望这一个能帮助你:) 您只需将ListCellRenderer添加到组合框中 class MyComboBoxRenderer extends JLabel implements ListCellRenderer { . . . public ComboBoxRenderer() { setOpaque(true);

我想将现有的jcombobox中的一个选择项(已添加项)更改为斜体?有什么方法可以做到这一点吗?

我希望这一个能帮助你:)

您只需将ListCellRenderer添加到组合框中

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;
}
. . .

}

通过
ListCellRenderer
控制
JComboBox
元素的呈现。请查看以了解更多详细信息