How to set icon in a column of JTable?
Asked Answered
E

3

5

I am able to set the column's header but not able to set icon in all the rows of first column of 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.

    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?

Engine answered 10/4, 2011 at 21:34 Comment(3)
What does this code do now? What specifically is wrong with it.Forcer
Also what is the point of the imageicon class. Just store the image in that column and use it directly instead of dealing with this other class.Forcer
Its seting column's header only.But want to put icon in all rows of first column.Engine
C
10

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:

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)
            {
                switch (column)
                {
                    case 0: return Icon.class;
                    default: return super.getColumnClass(column);
                }
            }
        };
        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();
            }
        });
    }

}
Culmiferous answered 10/4, 2011 at 23:48 Comment(0)
F
2

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 setCellRenderer on the column.

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 iconRenderer should be IconRenderer instead.

Forcer answered 10/4, 2011 at 21:43 Comment(0)
S
0

I know the post is a little old but it's never too late ...

I will post here how to insert an icon without using a DefaultTableCellRenderer class, I use this for when I will only show an icon on the screen in a simple way not very elaborate.

I do it in a simple way ... I always create some tablemodel creators in the classes that I inherit. I usually pass by parameter the list of titles and types of objects.

Method that creates the tablemodel in the upper class:

protected void createTableModel(String[] columns, Class[] types){
    String[] vetStr = new String[columns.length];
    boolean[] vetBoo = new boolean[columns.length];
    Arrays.fill(vetStr, null);
    Arrays.fill(vetBoo, false);
    table.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] { vetStr },
        columns
    ) {
        boolean[] canEdit = vetBoo;
        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
}

Inherited class constructor:

"See that here I set the type as ImageIcon.class for the column"

.... constructor....

super("Balança");        
String[] columns = {"#", "Nome", "Porta", "Padrão"};
Class[] types = {Long.class, String.class, String.class, ImageIcon.class};
**strong text**super.createTableModel(columns, types);

When I list the items on the tablemodel there I show the image.

list.forEach( obj -> {
    tableModel.addRow(new Object[]{
        obj.getId(),
        obj.getName(),
        obj.getPort(),
        (obj.getId() == Global.standardScale)? 
        new ImageIcon(getClass().getResource("./br/com/valentin/img/accept.png")): ""
    });
});
Stoneman answered 12/10, 2020 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.