简体   繁体   English

Java-在GUI中向JTable添加新行

[英]Java- adding a new row to a JTable in GUI

I have a simple Java GUI which is displaying an empty table and a few buttons. 我有一个简单的Java GUI,它显示一个空表和一些按钮。 I am now trying to add a listener to one of the buttons that will add a new empty row (with editable cells) to the table in the GUI. 我现在正尝试向其中一个按钮添加一个侦听器,这些按钮将向GUI中的表添加一个新的空行(具有可编辑的单元格)。

I am using the following code to try and do this: 我正在使用以下代码尝试执行此操作:

JButton addBtn = new JButton("Add");
addBtn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        System.out.println("'Add' button pressed. ");
        DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
        model.addRow(new Object[]{"Site", "Application", "Entity"});
        System.out.println("--- ActionListener added to 'addBtn' ---");
    }
});

However, when I click the button, I am getting a java.lang.ArrayIndexOutOfBoundsException . 但是,当我单击按钮时,出现了java.lang.ArrayIndexOutOfBoundsException It says that this is occurring on the following line: 它说这发生在以下行:

model.addRow(new Object[]{"Site", "Application", "Entity"});

I am not sure why I'm getting this exception... I've created a new Object[] array, and given it three elements... but I'm not trying to access those elements (or any elements that don't exist)... 我不确定为什么会收到此异常...我创建了一个新的Object[]数组,并为其指定了三个元素...但是我没有尝试访问那些元素(或任何不包含这些元素的元素)不存在)...

Can anyone point out what I'm doing wrong here? 谁能指出我在这里做错了什么?

I think this will work 我认为这会起作用

DefaultTableModel model = (DefaultTableModel) jEntityFilterTable.getModel();

Vector row = new Vector();
row.add("Site");
row.add("Application");
row.add("Entity");
model.addRow(row);

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

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