How to render an image to a JTable cell

前端 未结 2 1758
無奈伤痛
無奈伤痛 2021-01-20 15:37

I want to apply a renderer on a cell of my JTable, to do so I created a class named myRenderer :

import java.awt.Component;

import javax.swing.ImageIcon;
im         


        
2条回答
  •  攒了一身酷
    2021-01-20 16:32

    Besides the fact that you are not even properly overriding the getTableCellRendererComponent method, you don't even need a custom renderer to display an image in a column

    From How to Use Tables. Here's a list of types with default pre-configured renderers

    • Boolean — rendered with a check box.
    • Number — rendered by a right-aligned label.
    • Double, Float — same as Number, but the object-to-text translation is performed by a NumberFormat instance (using the default number format for the current locale).
    • Date — rendered by a label, with the object-to-text translation performed by a DateFormat instance (using a short style for the date and time).
    • ImageIcon, Icon — rendered by a centered label.
    • Object — rendered by a label that displays the object's string value.

    So you can put add an ImageIcon to the table and it will be rendered as such, given you properly override the getColumnClass()

    Also from tutorial:

    To choose the renderer that displays the cells in a column, a table first determines whether you specified a renderer for that particular column. If you did not, then the table invokes the table model's getColumnClass method, which gets the data type of the column's cells. Next, the table compares the column's data type with a list of data types for which cell renderers are registered

    So say you have a DefaultTableModel with three columns and you want an ImageIcon in the last column. You would do something like this

    DefaultTableModel model = new DefaultTableModel(...) {
        @Override
        public Class getColumnClass(int column) {
            switch (column) {
                case 2: return ImageIcon.class;
                default: return String.class
            }
        }
    };
    JTable table = new JTable(model);
    

    Then by just adding an ImageIcon to the third column, it will be rendered as such

    String colOneDate = "Data";
    String colTwoData = "Data";
    ImageIcon colThreeIcon = new ImageIcon(...);
    model.addRow(new Object[] { colOneData, colTwoData, colThreeIcon });
    

    You will probably also want to set the column widths and height accordingly, to the size of the image. For that you can see any of these questions

提交回复
热议问题