gpt4 book ai didi

java - 将行添加到 JTable 时出错

转载 作者:行者123 更新时间:2023-11-29 04:41:49 25 4
gpt4 key购买 nike

我有一个 JButton,一旦按下它,就会在 JTable 中添加一行。我试图通过实现以下代码来做到这一点。

columNames = new Vector<>();
columNames.addElement("Name");
columNames.addElement("CC");
columNames.addElement("Age");
columNames.addElement("PhoneNumber");
columNames.addElement("Date");
columNames.addElement("Amount$");

Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};

data = new DefaultTableModel(columNames, 0);
data.addRow(dataList);

table = new JTable(data);
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.setBounds(22, 78, 764, 177);
scrollTable.setViewportView(table);

//ActionListener method!.

if(e.getActionCommand().equals("Add client"))
{
Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};
data.addRow(dataList);

DefaultTableModel defaut = (DefaultTableModel) table.getModel();
defaut.addRow(dataList);
}

它抛出 Exception in thread "AWT-EventQueue-0"java.lang.ArrayIndexOutOfBoundsException:-1

我该如何解决?

最佳答案

如以下完整示例所示,您的片段似乎可以正常工作。该示例可以帮助您隔离完整代码中的问题。此外,

image

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
* @see https://stackoverflow.com/a/38926460/230513
*/
public class Test {

private final Object[] dataList = {"name", "cc", "age", "phone", "date", "amount"};

private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Vector columNames = new Vector<>();
columNames.addElement("Name");
columNames.addElement("CC");
columNames.addElement("Age");
columNames.addElement("Phone");
columNames.addElement("Date");
columNames.addElement("Amount$");
DefaultTableModel data = new DefaultTableModel(columNames, 0);
data.addRow(dataList);
JTable table = new JTable(data);
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.setViewportView(table);
f.add(new JScrollPane(table));
f.add(new JButton(new AbstractAction("Add") {
@Override
public void actionPerformed(ActionEvent e) {
data.addRow(dataList);
}
}), BorderLayout.PAGE_END);

f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}

关于java - 将行添加到 JTable 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com