Java Swing TableColumn set cell renderer

Description

Java Swing TableColumn set cell renderer

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main extends JPanel {
   public Main() {
      setLayout(new BorderLayout(5, 5));
      String[][] data = { /*from  w  w  w  .  j a  va  2s.c om*/
            { "", "", "1", "8", "8", "9", "7" },// 
            { "", "", "2", "7", "8", "8", "8" },//
            { "", "", "3", "8", "8", "9", "6" },//
            { "", "", "4", "8", "8", "9", "8" },//
            { "", "", "5", "8", "8", "9", "8" } //
          };
      String[] colHeaders = { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
      final JTable table = new JTable(data, colHeaders);

      TableColumn col = table.getColumnModel().getColumn(3);
      col.setCellRenderer(new MyTableCellRenderer());

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

class MyTableCellRenderer extends JLabel implements TableCellRenderer {
   public Component getTableCellRendererComponent(JTable table, Object value,
       boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {

     if (isSelected) {
       // cell (and perhaps other cells) are selected
     }

     if (hasFocus) {
       // this cell is the anchor and the table has the focus
     }

     // Configure the component with the specified value
     setText("**"+value.toString());

     // Set tool tip if desired
     setToolTipText((String) value);

     // Since the renderer is a component, return itself
     return this;
   }

   // The following methods override the defaults for performance reasons
   public void validate() {
   }

   public void revalidate() {
   }

   protected void firePropertyChange(String propertyName, Object oldValue,
       Object newValue) {
   }

   public void firePropertyChange(String propertyName, boolean oldValue,
       boolean newValue) {
   }
 }



PreviousNext

Related