java - 如何将图像插入到 JTable 单元格中

标签 java swing icons jtable

有人能为我指明正确的方向,告诉我如何将图像添加到 Java 表格单元格中吗。

最佳答案

JTable 已经为图标提供了默认渲染器。您只需要告诉表在给定列中存储了哪些数据,以便它可以选择合适的渲染器。这是通过覆盖 getColumnClass(...) 方法完成的:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JPanel
{
    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)
        {
            //  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();
            }
        };
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Icon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableIcon());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

}

关于java - 如何将图像插入到 JTable 单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4941372/

相关文章:

java - 确保 JCombo 操作仅在初始选择时执行?

java - 将自定义数据与 Swing 控件相关联?

java - 如何将图像图标设置为 JButton

windows - 如何以编程方式更改 Windows 可执行文件和 Mac 应用程序的图标?

java - 更新 JTable 单元格的 ImageIcon

java - 如何创建类似于默认 Windows 框的文件选择器?

java - 有没有办法获取正在运行的数据库的名称?

android - 如何获取带有 Activity 名称的 Activity 图标

java - 运行 JAR(Fxyz3d 库)时出现 FileSystemNotFoundException

java - 需要从 jvm 中删除 fusionreactor 条目