简体   繁体   English

更改JTable中的列标题

[英]Change column header in a JTable

This is my table right now : 这是我现在的桌子:

在此处输入图片说明

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. 但是,除非将鼠标悬停在Lecturer列标题上,否则列标题不会更改。

Even when i use table.repaint() after this code, it won't change. 即使在此代码后使用table.repaint() ,它也不会更改。 Do you guys have any idea how can I solve this issue ? 你们有什么主意我该如何解决这个问题?

Thanks. 谢谢。

JTableHeader header= table.getTableHeader();
TableColumnModel colMod = header.getColumnModel();
TableColumn tabCol = colMod.getColumn(0);
tabCol.setHeaderValue("Lecturersssss");
header.repaint();

Chalita's suggestion should work. Chalita的建议应该有效。 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);
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM