怎么在java.swing的comobobox里使用icon
时间: 2024-02-12 10:08:14 浏览: 28
要在Java Swing的JComboBox中使用图标,可以通过自定义渲染器实现。以下是一个简单的示例代码:
```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;
import javax.swing.ListCellRenderer;
public class IconComboBoxExample extends JFrame {
private JComboBox<String> comboBox;
public IconComboBoxExample() {
setTitle("Icon ComboBox Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 创建一个带图标的ComboBox
comboBox = new JComboBox<String>(new String[]{"Java", "Python", "C++"});
comboBox.setRenderer(new IconListCellRenderer());
getContentPane().add(comboBox);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// 自定义渲染器
class IconListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null) {
switch (value.toString()) {
case "Java":
label.setIcon(new ImageIcon(getClass().getResource("/java.png")));
break;
case "Python":
label.setIcon(new ImageIcon(getClass().getResource("/python.png")));
break;
case "C++":
label.setIcon(new ImageIcon(getClass().getResource("/cpp.png")));
break;
default:
label.setIcon(null);
break;
}
}
return label;
}
}
public static void main(String[] args) {
new IconComboBoxExample();
}
}
```
在这个例子中,我们创建了一个带有图标的JComboBox,并且自定义了一个渲染器IconListCellRenderer,根据每个选项的值设置相应的图标。注意,图标需要放在项目的resources目录下。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)