JTable with custom cell renderer example

Creating a JTable with custom cell renderer example


Often you need a JTable with some modified look and feel for JTable Cell , we need to use custom cell renderer for JTable. Lets see how we can use JTable cell renderer to customize the look and feel of the JTable cell. As shown in example below we are creating a class CustomTableCellRenderer which is implementing TableCellRenderer interface. We need to implement one and important method which is getTableCellRendererComponent() which accepts number of arguments such as

1. table - the JTable wihch we want to draw , it can be null too.

2. value - the value of the cell to be rendered.It can be null too.

3. isSelected - selection highlighting

4.hasFocus - if true, render cell appropriately.

5. row - the row index

6. column - the column index

In the getTableCellRendererComponent we are writing the logic to get the look and feel for each cell we want. We are treating component as JLabel


JTable with custom cell renderer example



Here we are creating class CustomTableCellRenderer and implementing of getTableCellRendererComponent.

class CustomTableCellRenderer extends JLabel implements TableCellRenderer {
  Color selColor;
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
      boolean hasFocus, int rowIndex, int vColIndex) {
    if (selColor instanceof Color) {
      selColor = (Color) value;
    } else {
      selColor = table.getBackground();
    }
    return this;
  }

  public void paint(Graphics g) {
    g.setColor(selColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}


Creating default table model for table.
  class CustomDefaultTableModel extends DefaultTableModel {
    public Class getColumnClass(int mColIndex) {
        int rowIndex = 0;
        Object o = getValueAt(rowIndex, mColIndex);
        if (o == null) {
          return Object.class;
        } else {
          return o.getClass();
        }
      }
  
}


Setting the cell renderer with setDefaultRenderer as below
public class JTableRendererExample {
  public static void main(String[] argv) {
    DefaultTableModel model = new CustomDefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("Table Renderer Example", new Object[] { Color.LIGHT_GRAY });
    model.addRow(new Object[] { Color.MAGENTA });
    model.addRow(new Object[] { Color.PINK });

    table.setDefaultRenderer(Color.class, new CustomTableCellRenderer());
    
    JFrame tableFrame = new JFrame();
    tableFrame.setSize(300,300);
    tableFrame.add(new JScrollPane(table));
    tableFrame.setVisible(true);
  }
}



Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment