//表JComboBox数据
String[] status = { "启用", "禁用", "停用" };
JComboBox com = new JComboBox(status);
JComboBoxRenderer select=new JComboBoxRenderer();
com.setRenderer(select);//ListCellRenderer监听
class JComboBoxRenderer extends JLabel implements ListCellRenderer {
public JComboBoxRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
Color background;
Color foreground;
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
background = Color.BLUE;
foreground = Color.WHITE;
// check if this cell is selected
} else if (isSelected) {
background = Color.RED;
foreground = Color.WHITE;
// unselected, and not the DnD drop location
} else {
background = Color.yellow;
foreground = Color.BLACK;
};
setBackground(background);
setForeground(foreground);
return this;
}
}
本文介绍如何为 JComboBox 控件创建自定义渲染器,并通过不同状态改变其背景颜色和文字颜色,实现美观且功能丰富的下拉列表显示效果。
1113

被折叠的 条评论
为什么被折叠?



