How to set icon in a column of JTable?

后端 未结 3 2088
[愿得一人]
[愿得一人] 2020-11-28 14:37

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 DefaultTableCellR         


        
3条回答
  •  我在风中等你
    2020-11-28 15:21

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

提交回复
热议问题