2016-08-12 117 views
1

我有一個JButton,一旦它被按下,就會將行添加到JTable中。我試圖通過實現下面的代碼來做到這一點。將行添加到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

我該如何解決呢?

+2

你的ActionListener似乎試圖添加DataList控件數組表模型** **兩次,通過數據對象一次,通過提取臺式一次 - 爲什麼?爲什麼不嘗試簡單地添加一次? –

+2

如果TrashGod的回答不能幫助你解決問題,那麼請考慮創建併發佈一個有效的[mcve],一個小型自包含程序來演示你的問題,類似於下面已經發布的垃圾內容。 –

+0

@HovercraftFullOfEels我試圖添加兩次cuz第二個是一個Action監聽器,將添加一個新的行。 – Cohen

回答

3

如下面的完整示例所示,您的碎片顯示正常工作。該示例可以幫助您在完整代碼中隔離問題。此外,

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