1

This is my table right now :

enter image description here

This is the code that I can change the column title:

table.getColumnModel().getColumn(0).setHeaderValue("Lecturersssss");

But the column title would not change until I hover the mouse on the Lecturer column header.

Even when i use table.repaint() after this code, it won't change. Do you guys have any idea how can I solve this issue ?

Thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Nathan Drake
  • 311
  • 3
  • 16

2 Answers2

4
JTableHeader header= table.getTableHeader();
TableColumnModel colMod = header.getColumnModel();
TableColumn tabCol = colMod.getColumn(0);
tabCol.setHeaderValue("Lecturersssss");
header.repaint();
chalitha geekiyanage
  • 6,464
  • 5
  • 25
  • 32
2

Chalita's suggestion should work. Here's sanity check short demonstration program. Click the button to change the column header text. Works on my environment at least...

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

public class TTT extends JFrame {
    JTable t;
    public TTT() {
        setLayout(new BorderLayout());
        Object[] cols= new Object[]{"Col1","Col2","Col3"};
        Object[][] vals= new Object[][]{{5,6,7}};
        t = new JTable(vals,cols);
        add(new JScrollPane(t),BorderLayout.CENTER);
        JButton b = new JButton("Change Column Header");
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Random r = new Random();
                Enumeration<TableColumn> e = t.getColumnModel().getColumns();
                while( e.hasMoreElements( ) )
                    e.nextElement().setHeaderValue("Col"+Math.abs(r.nextInt()));
                t.getTableHeader().repaint();
            }
        });
        b.setPreferredSize(new Dimension(1,25));
        add(b,BorderLayout.SOUTH);
        setSize(500,150);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TTT().setVisible(true);
            }
        });
    }
}
TT.
  • 15,774
  • 6
  • 47
  • 88