Java - 在 JTable 中渲染图像

Java - Rendering Image in JTable

我正在编写一个玩纸牌游戏的程序。我已经让游戏运行起来并有效地玩了它,但现在我决定添加卡片图像(现在它可以运行但使用卡片名称,如 "As of Spades",而不是图标来表示它们)。

在我的程序中,我使用 JTables 来组织卡片,并将它们的 selection 放在我放入的各种 JDialogs 中(一个用于交换的对话框手牌,另一张 select 要丢弃的牌,等等)

我尝试过,并且我个人喜欢它的工作方式,它为每张卡片制作一个具有 8 列和 1 行单元格的 JTable。在每个单元格内放一张卡片的图像。然后我会 select 一个单元格到 select 一张卡片,或者在 table.

之外使用 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" 是卡片文件的路径。我首先通过为所有单元格放置相同的卡片图像来测试我的代码。

乍一看我得到了想要的结果,图像显示正确,但是当点击它们几次时,table 将停止渲染它们,而是显示 toString() 的值图片:

Card Images in JTable(2)

Card Images in JTable(3)

然后图像将不再显示在 table 上。我只需要用户能够点击图像而不消失。

好的,感谢阅读。

DeR.

Object[] data = {new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel()}; 
dtModel.addRow(data);

不要将 JLabel 添加到模型中。相反,您需要添加一个 ImageIcon.

然后 JTable 将使用图标渲染器来显示图像。

Simple Example

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.

的自定义编辑器