如何将图像插入 JTable 单元格 [英] How to Insert Image into JTable Cell

查看:36
本文介绍了如何将图像插入 JTable 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能指出我如何将图像添加到 Java Table 单元格的正确方向.

Can someone point me in the right direction on how to add an image into Java Table cell.

推荐答案

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

JTable already provides a default renderer for icons. You just need to tell the table what data is stored in a given column so it can choose the appropriate renderer. This is done by overriding the getColumnClass(...) method:

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();
            }
        });
    }

}

这篇关于如何将图像插入 JTable 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆