我需要实现一个图像列表,用户可以通过拖放来移动。这就是我正在使用的代码:
...
model = new DefaultListModel();
imageList = new JList(model);
imageList.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
imageList.setTransferHandler(new ListItemTransferHandler());
imageList.setDropMode(DropMode.INSERT);
imageList.setDragEnabled(true);
imageList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
imageList.setVisibleRowCount(1);
imageList.setFixedCellWidth(405);
imageList.setFixedCellHeight(height);
imageList.setCellRenderer(new IconCellRenderer());
然后我将文件加载为 BufferedImages 并将它们添加到模型中
我的 IonCellRenderer 类如下:
class IconCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
private int size1;
private int size2;
private int spostamento;
private BufferedImage icon;
IconCellRenderer() {
this(400,600);
}
IconCellRenderer(int size1,int size2) {
this.size1 = size1;
this.size2 = size2;
spostamento = 4;
icon = new BufferedImage(size1,size2,BufferedImage.TYPE_INT_ARGB);
}
@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 BufferedImage) {
JLabel l = (JLabel)c;
l.setText("");
BufferedImage i = (BufferedImage)value;
l.setIcon(new ImageIcon(icon));
Graphics2D g = icon.createGraphics();
g.setColor(new Color(0,0,0,0));
g.clearRect(spostamento, 0, size1, size2);
g.drawImage(i,spostamento,0,size1,size2,this);
g.dispose();
}
return c;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(size1, size2);
}
}
但是,当我运行代码时,它可以工作,但显示的图像质量很差,而且它们没有显示一些线条。我不知道这是否可能是因为图像的大小有点大(即 1488x2105),我将它们调整为 400x600。
我该如何解决?
谢谢你的建议, Stefano Franchini