Java 动态添加列到 JTable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2443008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:44:04  来源:igfitidea点击:

Adding Columns to JTable dynamically

javaswinguser-interfacejtable

提问by jonasespelita

I have an empty JTable, absolutely nothing in it. I need to dynamically generate its table columns in a certain way. A simplified version for the code I have for my attempt:

我有一个空的 JTable,里面什么都没有。我需要以某种方式动态生成它的表列。我尝试使用的代码的简化版本:

@Action
public void AddCol() {
    for (int i = 0; i < 10; i++) {
        TableColumn c = new TableColumn(i);
        c.setHeaderValue(getColNam(i));
        table.getColumnModel().addColumn(c);
    }
}

But I'm getting an

但我得到了

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

线程“AWT-EventQueue-0”中的异常 java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

What am I doing wrong?

我究竟做错了什么?

Here's the complete stacktrace if it helps:

如果有帮助,这是完整的堆栈跟踪:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
        at java.util.Vector.elementAt(Vector.java:427)
        at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:632)
        at engine.Processor$UpdateTable.run(Processor.java:131)
        at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

采纳答案by Russ Hayward

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);
        }
    }
}

回答by Peter Lang

We don't have the complete StackTrace, so I can't tell for sure, but I guess that the exception is thrown at getColNam(i)where you could be referring to some empty Collection.

我们没有完整的 StackTrace,所以我不能肯定,但我想异常是在getColNam(i)您可能引用一些空集合的地方引发的。

Try to replace it by

尝试将其替换为

c.setHeaderValue("Test");

to find out.

找出答案。



If this is not the problem, you could try the TableColumn-Constructor without parameter:

如果这不是问题,您可以尝试TableColumn不带参数的-Constructor:

TableColumn c = new TableColumn();

回答by Lourens Oberholzer

If you want to add a list of string column names in a quick way, use this.

如果要快速添加字符串列名称列表,请使用此方法。

DefaultTableModel tableModel = new DefaultTableModel();

for(String columnName : columnNames){
   tableModel.addColumn(columnName);
}

jTable.setModel(tableModel);