Custom Jtable Header has different layout then the other headers

2k views Asked by At

I have a table with 3 columns, the first column is special and contains a checkbox instead of a title.

The problem is that the layout (appareance) of the checkbox header is different from the other headers. Can anyone help?

The Code:

import java.awt.*;  
import javax.swing.*;  
import javax.swing.table.*;  
import java.awt.event.*; 

public class JTableHeaderCheckBox  
{  
  Object colNames[] = {"", "String", "String"};  
  Object[][] data = {};  
  DefaultTableModel dtm;  
  JTable table;  
  public void buildGUI()  
  {  
    dtm = new DefaultTableModel(data,colNames);  
    table = new JTable(dtm);  
    for(int x = 0; x < 2; x++)  
    {  
      dtm.addRow(new Object[]{new Boolean(false),"Row "+(x+1)+" Col 2","Row "+(x+1)+" Col 3"});  
    }  
    JScrollPane sp = new JScrollPane(table);  
    TableColumn tc = table.getColumnModel().getColumn(0);  
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));  
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));  
    tc.setHeaderRenderer(new CheckBoxHeader());  
    JFrame f = new JFrame();  
    f.getContentPane().add(sp);  
    f.pack();  
    f.setLocationRelativeTo(null);  
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    f.setVisible(true);  
  }  

  public static void main (String[] args)  
  {  
    SwingUtilities.invokeLater(new Runnable(){  
      public void run(){  
        new JTableHeaderCheckBox().buildGUI();  
      }  
    });  
  }  
}  

class CheckBoxHeader extends JCheckBox implements TableCellRenderer {  
    protected CheckBoxHeader rendererComponent;  
    protected int column;  

    public CheckBoxHeader() {  
        rendererComponent = this;   
    }  

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {  
        setColumn(column);   
        return rendererComponent;  
    }  

    protected void setColumn(int column) {  
        this.column = column;  
    }  
    public int getColumn() {  
        return column;  
    }    
} 

The wierd output:

enter image description here

UPDATE:
What I want:

  1. Center align the checkbox in the header
  2. If you pay close attention, you notice the background of the checkbox Header (it seems popping to the inside) is different from the other 2 headers (they seem popping out)
2

There are 2 answers

2
tenorsax On BEST ANSWER

If you're referring to the border of the checkbox you can try this to make the header look more consistent:

public CheckBoxHeader() {  
    rendererComponent = this;  

    setHorizontalAlignment(JLabel.CENTER);
    setBorderPaintedFlat(true);
    setBorderPainted(true);
}  
8
mKorbel On

TableCellRenderer returns JLabel/JComponents and these JComponents haven't got implemented any LayoutManager, but there isn't any restictions for setting some of LayoutManagers