Java JTable get rendered component at table cell

Description

Java JTable get rendered component at table cell

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


class MyDefaultTableModel extends DefaultTableModel {
   /*from w  w w  .ja  v a2  s .  c  o m*/

   public Class getColumnClass(int mColIndex) {
     int rowIndex = 0;
     Object o = getValueAt(rowIndex, mColIndex);
     if (o == null) {
       return Object.class;
     } else {
       return o.getClass();
     }
   }
 }
public class Main extends JPanel {
   public Main() {
      setLayout(new BorderLayout(5, 5));
      DefaultTableModel model = new MyDefaultTableModel();
      
      JTable table = new JTable(model);

      // Add data
      model.addColumn("Col1", new Object[] { Color.red });
      model.addRow(new Object[] { Color.green });
      model.addRow(new Object[] { Color.blue });

      Component renderer = getRenderedComponentAt(table,1,0);
      System.out.println(renderer);
      
      JScrollPane sp = new JScrollPane(table);

      add(sp, BorderLayout.CENTER);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
   
   public static Component getRenderedComponentAt(JTable table,
         int rowIndex, int columnIndex) {
     return table.getCellRenderer(rowIndex, columnIndex)
             .getTableCellRendererComponent(table,
                     table.getValueAt(rowIndex, columnIndex),
                     table.isCellSelected(rowIndex, columnIndex), false,
                     rowIndex, columnIndex);
 }
}



PreviousNext

Related