Java DefaultTableCellRenderer create custom cell renderer

Description

Java DefaultTableCellRenderer create custom cell renderer

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

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

class TableCellRenderer extends DefaultTableCellRenderer {
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
         int row, int column) {
      // Inherit the colors and font from the header component
      if (table != null) {
         JTableHeader header = table.getTableHeader();
         if (header != null) {
            setForeground(header.getForeground());
            setBackground(header.getBackground());
            setFont(header.getFont());//from   w w w  . j  a v a  2  s.  c om
         }
      }

      if (value instanceof Icon) {
         // Value is an Icon
         setIcon((Icon) value);
         setText("");
      } else {
         // Value is text
         setText((value == null) ? "" : value.toString());
         setIcon(null);
      }
      setBorder(UIManager.getBorder("TableHeader.cellBorder"));
      setHorizontalAlignment(JLabel.CENTER);
      return this;
   }
}

public class Main extends JPanel {
   public Main() {
      setLayout(new BorderLayout(5, 5));
      DefaultTableModel model = new DefaultTableModel();

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

      table.getColumnModel().getColumn(0).setHeaderValue(new SquareIcon());

      // Finally, set the icon header renderer on the second column
      table.getColumnModel().getColumn(0).setHeaderRenderer(new TableCellRenderer());

      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 SquareIcon implements Icon {
   private static final int SIZE = 10;

   public void paintIcon(Component c, Graphics g, int x, int y) {
      if (c.isEnabled()) {
         g.setColor(Color.RED);
      } else {
         g.setColor(Color.GRAY);
      }

      g.fillRect(x, y, SIZE, SIZE);
   }

   public int getIconWidth() {
      return SIZE;
   }

   public int getIconHeight() {
      return SIZE;
   }
}



PreviousNext

Related