在JList中添加图标。实现代码如下。
先新建一个实现ListCellRenderer接口的类,该接的getListCellRendererComponent返回的是一个Component。因此此类可以继承任何一个Component控件来体现显示的内容。一般继承JLabel,因为它即可显示图标也能显示文字。
class listView extends JLabel implements ListCellRenderer {
private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public listView() {
setOpaque(true);
setIconTextGap(5);
}
public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) {
listIcon item = (listIcon)value;
this.setIcon(item.getIcon());
this.setText(item.getText());
if (isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
}
然后在建立一个新类,用于描述列表项目中的文字和图标。
import javax.swing.*;
class listIcon{
Icon icon;
String text;
public listIcon(String icon, String text){
this.icon =new ImageIcon(icon);
this.text = text;
}
public Icon getIcon() {
return icon;
}
public String getText() {
return text;
}
}
有了这两个类,我们就可以很轻松的网JList内添加图标了。
如:
JList list = new JList();
list.setCellRenderer(new listView() ); //安装我们自订的cellRenderer
DefaultListModel listModel = new DefaultListModel();
list.setModel(listModel);
listIcon item = new listIcon("*.gif","test");
listModel.addElement(item); // 为List增加Item
在操作中如要获取列表的内容,代码如下:
listIcon item=(listIcon)listModel.get(index);
item.getText(): //这就是列表中第index项的文字内容.
先新建一个实现ListCellRenderer接口的类,该接的getListCellRendererComponent返回的是一个Component。因此此类可以继承任何一个Component控件来体现显示的内容。一般继承JLabel,因为它即可显示图标也能显示文字。
class listView extends JLabel implements ListCellRenderer {
private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public listView() {
setOpaque(true);
setIconTextGap(5);
}
public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) {
listIcon item = (listIcon)value;
this.setIcon(item.getIcon());
this.setText(item.getText());
if (isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
}
然后在建立一个新类,用于描述列表项目中的文字和图标。
import javax.swing.*;
class listIcon{
Icon icon;
String text;
public listIcon(String icon, String text){
this.icon =new ImageIcon(icon);
this.text = text;
}
public Icon getIcon() {
return icon;
}
public String getText() {
return text;
}
}
有了这两个类,我们就可以很轻松的网JList内添加图标了。
如:
JList list = new JList();
list.setCellRenderer(new listView() ); //安装我们自订的cellRenderer
DefaultListModel listModel = new DefaultListModel();
list.setModel(listModel);
listIcon item = new listIcon("*.gif","test");
listModel.addElement(item); // 为List增加Item
在操作中如要获取列表的内容,代码如下:
listIcon item=(listIcon)listModel.get(index);
item.getText(): //这就是列表中第index项的文字内容.