且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态添加列到 JTable

更新时间:2023-12-03 12:14:16

我认为您需要将列添加到表的数据模型及其列模型中.列模型在数据模型更改时更新,因此更改数据模型就足够了.下面是一个例子:

I think you need to add the column to your table's data model as well as its column model. The column model is updated when the data model changes so changing the data model should be sufficient. Here is an example:

public class TableColumnAdd {
    private static DefaultTableModel tableModel;
    private static int columnNumber = 1;

    public static void main(String[] args) throws InterruptedException, InvocationTargetException {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                tableModel = new DefaultTableModel(new Object[] { "Initial Column" }, 5);
                JTable table = new JTable(tableModel);
                JFrame frame = new JFrame("Table Column Add");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setBounds(100, 100, 600, 300);
                frame.add(new JScrollPane(table));
                frame.setVisible(true);
            }
        });

        for (;;) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    tableModel.addColumn("Column #" + columnNumber++);
                }
            });
            Thread.sleep(2000);
        }
    }
}