我想在我的JTable的单元格上应用渲染器,为此我创建了一个名为myRenderer的类:
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class MyRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table, ImageIcon icon) {
setIcon(icon);
return this;
}
}
我使用这段代码在单元格上应用渲染器:
MyRenderer renderer = new MyRenderer();
renderer.getTableCellRendererComponent(table, icon);
table.getColumnModel().getColumn(6).setCellRenderer(renderer);
问题是,rebderer应用于第6列中的所有单元格,我希望它仅应用于一个单元格(行/列),但我不知道该怎么做?
提前致谢
解决方法:
除了您甚至没有正确覆盖getTableCellRendererComponent方法之外,您甚至不需要自定义渲染器来在列中显示图像
从How to Use Tables开始.这是带有默认预配置渲染器的类型列表
> Boolean – 使用复选框呈现.
> Number – 由右对齐标签呈现.
> Double,Float – 与Number相同,但是对象到文本的转换由NumberFormat实例执行(使用当前语言环境的默认数字格式).
> Date – 由标签呈现,由DateFormat实例执行对象到文本的转换(使用日期和时间的简短样式).
> ImageIcon,Icon – 由居中标签呈现.
>对象 – 由显示对象字符串值的标签呈现.
因此,您可以将一个ImageIcon添加到表中,并且如果您正确覆盖了getColumnClass(),它将被呈现为这样
同样来自教程:
To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model’s getColumnClass method, which gets the data type of the column’s cells. Next, the table compares the column’s data type with a list of data types for which cell renderers are registered
因此,假设您有一个包含三列的DefaultTableModel,并且您希望在最后一列中使用ImageIcon.你会做这样的事情
DefaultTableModel model = new DefaultTableModel(...) {
@Override
public Class> getColumnClass(int column) {
switch (column) {
case 2: return ImageIcon.class;
default: return String.class
}
}
};
JTable table = new JTable(model);
然后只需将ImageIcon添加到第三列,它就会被渲染
String colOneDate = "Data";
String colTwoData = "Data";
ImageIcon colThreeIcon = new ImageIcon(...);
model.addRow(new Object[] { colOneData, colTwoData, colThreeIcon });
您可能还需要相应地将列宽和高度设置为图像的大小.为此你可以看到任何these questions
标签:renderer,java,swing,jtable,cell
来源: https://codeday.me/bug/20190825/1715510.html
本文介绍了如何在Java Swing的JTable中应用图像渲染,特别是如何将图像渲染到特定单元格。通过创建一个自定义的`MyRenderer`类并设置列的单元格渲染器,然后通过覆盖`getColumnClass`方法指定列的数据类型为`ImageIcon`,可以实现这一目标。当在表格模型中添加`ImageIcon`对象时,它们将自动以图像形式显示。同时,需要注意调整单元格的宽度和高度以适应图像大小。
1070

被折叠的 条评论
为什么被折叠?



