javastringswingjtableimageicon

JTable ImageIcon and String


I want to create a JTable where in the cells there could be an ImageIcon, String or both. I've already tried solutions like table.setvalue() or just adding the Icon to the Object Array for creating the JTable.

for (int n = 0; n < tableHeight; n++) {
  for (int m = 0; m < tableWidth; m++) {
    if ((n + m) == labelArray.size()) {
      break;
    }

    if (labelArray.get(n + m).iconMode) {  //iconMode is True if there is an icon instead of line text
      data[n][m] = null;
    } else {
      String text = new String("<html><p>" + labelArray.get(n + m).lineOne + "<br>" + labelArray.get(n + m).lineTwo + "<p></html>");
      data[n][m] = text;
    }
  }
}

table = new JTable(data, columnNames);

renderer = new DefaultTableCellRenderer();
renderer.setHorizontalTextPosition(JLabel.CENTER);
renderer.setHorizontalAlignment(JLabel.CENTER);

for (int n = 0; n < tableWidth; n++) {
  table.getColumnModel().getColumn(n).setCellRenderer(renderer);
  table.getColumnModel().getColumn(n).setWidth(50);
}

Solution

  • there could be an ImageIcon, String or both.

    You will need to create a custom object to store in the TableModel. This object will contain two properties:

    1. text
    2. icon

    Then you will need to create a custom renderer (not use the default renderer) to display this object.

    The custom renderer might look something like:

    class IconTextRenderer extends DefaultTableCellRenderer
    {
        public IconTextRenderer()
        {
            super();
            setHorizontalTextPosition(JLabel.CENTER);
            setHorizontalAlignment(JLabel.CENTER);
        }
    
        @Override
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    
            IconText iconText = (IconText)value;
            setIcon( iconText.getIcon() );
            setText( iconText.getText() );
    
            return this;
        }
    }
    

    You set the renderer for a single column by using:

    table.getColumnModel().getColumn(???).setCellRenderer( new IconTextRenderer());
    

    or for all columns using the custom class:

    table.setDefaultRenderer(IconText.class, new IconTextRenderer());