我创建了一个从网址a获取的图像数组,我希望将它们显示在一个列中,每行中都有一个新图像。据我所知,代码正在做正确的事情,但是在用于包含每个图像的单元格中,它会为每个图像返回BufferedImage @ ....
Document doc = Jsoup.connect(crawlUrlp).get();
Elements img = thumbnails.select("img");
for (Element a : img) {
URL url = new URL(a.attr("src"));
BufferedImage[] imge = {ImageIO.read(url)};
for (int i = 0; i < imge.length; i++) {
format.addRow(new BufferedImage[]{imge[i]});
}
}
然后我写了一个图像单元格渲染器:
public class BufferedImageCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value instanceof BufferedImage) {
setIcon(new ImageIcon((BufferedImage) value));
setText(null);
}
return this;
}
}
这似乎做得不多。我是否正确地认为,尽管输出结果为'BufferedImage',我实际上已经生成了一个字符串数组?如何显示这些图像?
答案 0 :(得分:1)
然后我写了一个图像单元格渲染器:
无需创建自定义渲染器。
相反,您应该在TableModel中存储图像图标:
//format.addRow(new BufferedImage[]{imge[i]});
format.addRow(new Object[]{new ImageIcon(imge[i])});
现在您需要覆盖TableModel以告诉表您正在模型中存储图标,以便表可以使用正确的渲染器。类似的东西:
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
@Override
public Class getColumnClass(int column)
{
return (column == 0) ? Icon.class : super.getColumnClass(column);
}
};
一个显示概念的简单示例:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableIcon extends JFrame
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("about16.gif");
Icon addIcon = new ImageIcon("add16.gif");
Icon copyIcon = new ImageIcon("copy16.gif");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "About"},
{addIcon, "Add"},
{copyIcon, "Copy"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable( model )
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
new TableRowResizer(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);
tca.adjustColumns();
}
public static void main(String[] args)
{
TableIcon frame = new TableIcon();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}