我正在编写一个程序来玩纸牌游戏。我已经让游戏运行起来,并且有效地玩它,但现在我决定添加纸牌图像(现在它可以运行,但使用纸牌名称,例如“黑桃”,而不是代表它们的图标)。
在我的程序中,我使用 JTable
来组织卡片,并在放置它们的各种 JDialog
中选择它们(一个用于交换卡片的对话框)手牌,另一张选择要丢弃的牌等)
我尝试过,而且我个人喜欢它的工作方式,它是为每张卡创建一个包含 8 列和 1 行单元格的 JTable
。每个单元格内都放有卡片的图像。然后,我会选择一个单元格来选择一张卡片,或者在表格外部使用 JButtonGroup
。
DefaultTableModel dtModel = new DefaultTableModel(COL_NAMES, 0) {
@Override
public Class<?> getColumnClass(int column) {
if (getRowCount() > 0)
return getValueAt(0, column).getClass();
return super.getColumnClass(column);
}
};
//add the columns to the model:
if (dtModel.getColumnCount() == 0) {
for (int i = 0; i < COLS; i++) {
dtModel.addColumn(COL_NAMES[i]);
}
}
//add a row to the model:
if (dtModel.getRowCount() == 0) {
Object[] data = {new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel()};
dtModel.addRow(data);
}
jTable1.setModel(dtModel);
//set the size of the table, but I think I got it wrong:
jScrollPane1.setSize(400, jScrollPane1.getColumnHeader().getHeight() + jTable1.getRowHeight());
//here is the image I'm using:
ImageIcon ii = new ImageIcon("C:\\Users\\DeRipper\\Pictures\\Naipes\\oros_1s.jpg");
//the loop where I set the image in all the cells. I scale the image into a smaller size:
for (int i = 0; i < COLS; i++)
jTable1.setValueAt(new ImageIcon(ii.getImage().getScaledInstance(50, 65, Image.SCALE_DEFAULT)), 0, i);
其中“C:\\Users\\DeRipper\\Pictures\\Naipes\\oros_1s.jpg”
是卡片文件的路径。我首先通过为所有单元格放置相同的卡片图像来测试我的代码。
乍一看,我得到了想要的结果,图像显示正确,但是当单击它们几次时,表格将停止渲染它们,而是显示 toString()
值图片:
然后图像将不再显示在 table 上。我只需要用户能够单击图像而不消失。
好的,感谢您的阅读。
德鲁。
最佳答案
Object[] data = {new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel()};
dtModel.addRow(data);
不要将 JLabel
添加到模型中。相反,您需要添加一个 ImageIcon
。
然后JTable
将使用图标渲染器来显示图像。
but when clicking on them a couple of times the table would stop rendering them and instead showing the "toString()" value of the images:
如果您正在编辑单元格,则默认编辑器只会将对象的 toString()
表示形式保存回 TableModel。因此,您可能需要重写 isCellEditable(...) 方法来关闭编辑。否则,您将需要一个知道如何编辑和保存 ImageIcon
的自定义编辑器。
关于Java - 在 JTable 中渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070147/