怎么在java.swing的comobobox里使用icon
时间: 2024-02-12 20:05:05 浏览: 117
要在Java Swing的Combobox里使用icon,您需要自定义Combobox的渲染器(renderer),以便能够在下拉列表中显示图标。下面是一个简单的示例代码:
```java
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
public class IconComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("IconComboBox Example");
String[] items = {"Item 1", "Item 2", "Item 3"};
ImageIcon[] icons = {new ImageIcon("icon1.png"), new ImageIcon("icon2.png"), new ImageIcon("icon3.png")};
JComboBox<String> comboBox = new JComboBox<String>(items);
comboBox.setRenderer(new IconListRenderer(icons));
frame.add(comboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class IconListRenderer extends DefaultListCellRenderer {
private ImageIcon[] icons;
public IconListRenderer(ImageIcon[] icons) {
this.icons = icons;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setIcon(icons[index]);
return label;
}
}
```
在上面的示例中,我们自定义了一个IconListRenderer类来实现Combobox的渲染器。该类继承自DefaultListCellRenderer类,并覆盖了getListCellRendererComponent()方法,以便在Combobox的下拉列表中显示图标。在getListCellRendererComponent()方法中,我们使用了setIcon()方法来设置每个项的图标。
希望这个示例对您有所帮助!
阅读全文