java 如何在JTable的一列中设置图标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5614875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:55:29  来源:igfitidea点击:

How to set icon in a column of JTable?

javaswingjtabletablemodelcellrenderer

提问by bsm

I am able to set the column's header but not able to set icon in all the rows of first column of JTable.

我可以设置列的标题,但不能在 JTable 第一列的所有行中设置图标。

public class iconRenderer extends DefaultTableCellRenderer{
    public Component getTableCellRendererComponent(JTable table,Object obj,boolean isSelected,boolean hasFocus,int row,int column){
        imageicon i=(imageicon)obj;
        if(obj==i)
            setIcon(i.imageIcon);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(JLabel.CENTER);
        return this;
    }
}

public class imageicon{
    ImageIcon imageIcon;
    imageicon(ImageIcon icon){
        imageIcon=icon;
    }
}  


and below lines in my BuildTable() method.

以及我的 BuildTable() 方法中的以下几行。

    public void SetIcon(JTable table, int col_index, ImageIcon icon){
      table.getTableHeader().getColumnModel().getColumn(col_index).setHeaderRenderer(new iconRenderer());
      table.getColumnModel().getColumn(col_index).setHeaderValue(new imageicon(icon));
}


How can we set it for all rows of first columns? I have tried with for loop but didnt get yet for rows to iterate to set icon. Or is there any other way?

我们如何为第一列的所有行设置它?我已经尝试过 for 循环,但还没有得到用于迭代设置图标的行。或者还有其他方法吗?

回答by camickr

There is no need to create a custom render. JTable already supports an Icon renderer. YOu just need to tell the table to use this renderer. This is done by overriding the getColumnClass(...) method of the table model:

无需创建自定义渲染。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();
            }
        });
    }

}

回答by jzd

You are just using iconRenderer for the render of your header. Also set the Column's Cell Reneder to be an instance of iconRenderer as well. Call setCellRendereron the column.

您只是使用 iconRenderer 来渲染标题。还要将 Column 的 Cell Reneder 设置为 iconRenderer 的一个实例。调用setCellRenderer列。

http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setCellRenderer(javax.swing.table.TableCellRenderer)

http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setCellRenderer(javax.swing.table.TableCellRenderer)

Side note: Java coding standards specify that class names should start with capital letters, so iconRenderershould be IconRendererinstead.

旁注:Java 编码标准规定类名应该以大写字母开头,所以iconRenderer应该IconRenderer改为。