Java - 在 JTable 中渲染图像

标签 java image swing jtable

我正在编写一个程序来玩纸牌游戏。我已经让游戏运行起来,并且有效地玩它,但现在我决定添加纸牌图像(现在它可以运行,但使用纸牌名称,例如“黑桃”,而不是代表它们的图标)。

在我的程序中,我使用 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() 值图片:

Card Images in JTable(2)

Card Images in JTable(3)

然后图像将不再显示在 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将使用图标渲染器来显示图像。

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 的自定义编辑器。

关于Java - 在 JTable 中渲染图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35070147/

相关文章:

java - 在 weblogic 12c 中添加数据源

Java KeyListener 没有检测到键盘输入

java - 以列表作为参数的 spring-data 查询方法

java - 如何使我的应用程序在选择时以及用户选择文件夹时读取我的文件,然后使应用程序读取其中的所有文件?

c++ - 十六进制数据 (RGB888) 中的图像文件到 BMP、JPG、PNG 或其他格式

C#打印像素值

java - 为我的JAVA算命先生程序生成不重复的算命?

java - Gridbag布局问题

java - 为什么java swing的setVisible要这么久?

java - 执行 SQL 的标准是什么?