Search code examples
javaswingjtablejtableheader

How to make the defaulttablemodel table header bold


I want to make the header of a jtable with defaulttablemodel BOLD. Here's my code

class TablePanel extends JPanel {

    private String[] COLUMNS = {"FAMILY MEMBERS", "STAR (NAKSHATRA)"};
       private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0){

        public boolean isCellEditable(int row, int column) {
                return false;
           }

       };
       DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(){

        public void setHorizontalAlignment(int alignment) {
               alignment = (int) CENTER_ALIGNMENT;
           };

       };
       public JTable table = new JTable(model){
         public void setDefaultRenderer(java.lang.Class<?> columnClass, TableCellRenderer renderer) {
             columnClass= String.class;
             renderer=centerRenderer;
         };  
         public void setBackground(Color bg) {
             bg = Color.yellow;
         };

       };

I want to make the column headers BOLD. any hint on this is appreciated


Solution

  • Strangely enough, a table column header uses the same concept to renderer as the table does...

    DefaultTableCellRenderer header = new DefaultTableCellRenderer();
    header.setFont(header.getFont().deriveFont(Font.BOLD));
    JTable table = new JTable();
    TableColumnModel model = table.getColumnModel();
    model.getColumn(0).setHeaderRenderer(header);
    

    For example. But I don't think it will turn out the way you want it to...

    Instead, you could try something like...

    DefaultTableModel model = new DefaultTableModel(new Object[]{"<html><b>Happy</b></html>", "Sad"}, 0);
    JTable table = new JTable(model);
    

    enter image description here