考虑这种替代方法,我们正在处理Product 形式的一组对象,这些对象使用自定义单元格渲染器在JList 中显示属性productName 和energyConsumption。
输出
User Selected:
Product name: Ducted Heating power consumption: 5000
Product name: Home Theater power consumption: 8000
Product name: Heated Pool power consumption: 12000
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ListIterator;
import javax.swing.*;
public class ProductSelector {
public static void main(String[] args) {
final Product[] products = {
new Product("None", 0),
new Product("Ducted Heating", 5000),
new Product("Home Theater", 8000),
new Product("Heated Spa", 3500),
new Product("Heated Pool", 12000)
};
Runnable r = new Runnable() {
@Override
public void run() {
JList list = new JList(products);
list.setVisibleRowCount(products.length);
list.setCellRenderer(new ProductCellRenderer(30));
JOptionPane.showMessageDialog(null, new JScrollPane(list));
java.util.List selected = list.getSelectedValuesList();
ListIterator li = selected.listIterator();
System.out.println("User Selected:");
while (li.hasNext()) {
System.out.println(li.next());
}
}
};
SwingUtilities.invokeLater(r);
}
}
class ProductCellRenderer extends DefaultListCellRenderer {
int scale;
ProductCellRenderer(int scale) {
this.scale = scale;
}
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
if (c instanceof JLabel && value instanceof Product) {
JLabel l = (JLabel) c;
Product product = (Product) value;
l.setHorizontalTextPosition(SwingConstants.TRAILING);
l.setVerticalTextPosition(SwingConstants.CENTER);
int width = product.getPowerConsumption() / scale;
int type = BufferedImage.TYPE_INT_RGB;
if (width > 0) {
BufferedImage bi = new BufferedImage(
width,
16,
type);
l.setIcon(new ImageIcon(bi));
}
l.setText(product.getProductName());
}
return c;
}
}
class Product {
private String productName;
private int powerConsumption;
public Product() {
}
public Product(String productName, int powerConsumption) {
this.productName = productName;
this.powerConsumption = powerConsumption;
}
/**
* @return the productName
*/
public String getProductName() {
return productName;
}
/**
* @param productName the productName to set
*/
public void setProductName(String productName) {
this.productName = productName;
}
/**
* @return the powerConsumption
*/
public int getPowerConsumption() {
return powerConsumption;
}
/**
* @param powerConsumption the powerConsumption to set
*/
public void setPowerConsumption(int powerConsumption) {
this.powerConsumption = powerConsumption;
}
@Override
public String toString() {
return "Product name: " + productName
+ " power consumption: " + powerConsumption;
}
}