預設的JComboBox無法在每個條目上顯示表徵圖、縮排等樣式。但是Swing的MVC設計結構為各種組件提供了無與倫比的可擴充性。為了實現這一點,我們可以建立一個新的Renderer來負責每個條目的繪製。
首先我們新寫一個類ImagedComboBoxItem,它封裝了一個下拉條目的資訊,包括表徵圖、文字、縮排等:
class ImagedComboBoxItem {
private Icon icon = null;
private String text = null;
private int indent = 0;
ImagedComboBoxItem(String text, Icon icon, int indent) {
this.text = text;
this.icon = icon;
this.indent = indent;
}
public String getText() {
return text;
}
public Icon getIcon() {
return icon;
}
public int getIndent() {
return indent;
}
}
然
後建立JImagedComboBox類並從JComboBox繼承。在建構函式中,建立一個DefaultListCellRenderer作為新的
Renderer,並覆蓋其getListCellRendererComponent方法。在新的
getListCellRendererComponent方法中,首先依舊調用父物件的該方法,以便完成普通條目的繪製;然後判斷條目是否是
ImagedComboBoxItem執行個體。如果是,則顯示ImagedComboBoxItem的文字、表徵圖,並顯示縮排。為了更方便的顯示左側縮排,
我們直接建立一個EmptyBorder並設定左側縮排數量,並設定到DefaultListCellRenderer中。
DefaultListCellRenderer從JLabel繼承而來,所以可直接接受各種Border。這裡我們以每個縮排10象素為例。
好了,以下是完整代碼:
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class JImagedComboBox extends JComboBox {
public JImagedComboBox(Vector values) {
super(values);
ListCellRenderer renderer = new DefaultListCellRenderer() {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof ImagedComboBoxItem) {
ImagedComboBoxItem item = (ImagedComboBoxItem) value;
this.setText(item.getText());
this.setIcon(item.getIcon());
if (isPopupVisible()) {
int offset = 10 * item.getIndent();
this.setBorder(BorderFactory.createEmptyBorder(0, offset, 0, 0));
}
}
return this;
}
};
this.setRenderer(renderer);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
Vector values = new Vector();
Icon openIcon = new ImageIcon(JImagedComboBox.class.getResource("Open16.gif"));
Icon newIcon = new ImageIcon(JImagedComboBox.class.getResource("New16.gif"));
for (int i = 0; i < 5; i++) {
values.addElement(new ImagedComboBoxItem("Directory " + i, openIcon, i));
}
for (int i = 0; i < 5; i++) {
values.addElement(new ImagedComboBoxItem("Image Item " + i, newIcon, 5));
}
JImagedComboBox comboBox = new JImagedComboBox(values);
frame.getContentPane().add(comboBox, BorderLayout.NORTH);
frame.show();
}
}
class ImagedComboBoxItem {
private Icon icon = null;
private String text = null;
private int indent = 0;
ImagedComboBoxItem(String text, Icon icon, int indent) {
this.text = text;
this.icon = icon;
this.indent = indent;
}
public String getText() {
return text;
}
public Icon getIcon() {
return icon;
}
public int getIndent() {
return indent;
}
}