2

我正在尝试向 JTable 动态添加行,但遇到 ArrayIndexOutOfBounds 异常时遇到了困难。我很困惑,因为没有具体解释为什么问题存在以及问题发生在哪里。请参阅下面的代码。

ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();
Object[][] data;

Random rand = new Random();

******************** WHEN PRESSING A BUTTON *****************************

matrix.add(new ArrayList<String>()); 
((ArrayList<String>)matrix.get(0)).add("row 0 col " + rand.nextInt(100) );
((ArrayList<String>)matrix.get(0)).add("row 0 col 1");
((ArrayList<String>)matrix.get(0)).add("row 0 col 2");
matrix.add(new ArrayList<String>()); 
((ArrayList<String>)matrix.get(1)).add("row 1 col 0");
((ArrayList<String>)matrix.get(1)).add("row 1 col 1");
((ArrayList<String>)matrix.get(1)).add("row 1 col 2");

data = new Object[matrix.size()][];

for(int i = 0; i < matrix.size(); i++){
    data[i] = matrix.get(i).toArray();
}

table = new JTable(data, new String[]{"A", "B", "C"});
table.setFillsViewportHeight(true);
table.setForeground(Color.WHITE);
table.setBackground(Color.BLACK);
table.setBounds(0, 0, 423, 91);

pnlTable.add(table);
pnlTable.setLayout(null);

table.updateUI();
System.out.println("done");

只有在按钮上按 2 次或更多次后才会出现此问题。谁能帮助我如何动态清空表并在其中添加新数据?

编辑:这是错误日志:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
    at javax.swing.JTable$1.getValueAt(Unknown Source)
    at javax.swing.JTable.getValueAt(Unknown Source)
    at javax.swing.JTable.prepareRenderer(Unknown Source)
    at javax.swing.plaf.basic.BasicTableUI.paintCell(Unknown Source)
    at javax.swing.plaf.basic.BasicTableUI.paintCells(Unknown Source)
    at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
    at javax.swing.plaf.ComponentUI.update(Unknown Source)
    at javax.swing.JComponent.paintComponent(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintToOffscreen(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    at javax.swing.RepaintManager.paint(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
    at javax.swing.RepaintManager.access$700(Unknown Source)
    at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
4

3 回答 3

3

要更改 JTable 的内容,请不要重新创建 JTable。只需为其创建一个新的 TableModel,例如 DefaultTableModel 对象或 AbstractTableModel 扩展类对象,然后通过setModel().

此外,您应该避免使用 null 布局,并且永远不要调用 updateUI,除非您正在更改 GUI 的外观和感觉。

例如,

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.Arrays;
import java.util.Vector;
import java.util.Random;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class TableFoo extends JPanel {
   private static final Vector<String> COLUMN_NAME_VECTOR = new Vector<String>(
         Arrays.asList(new String[] { "A", "B", "C" }));
   private static final int COLUMN_COUNT = COLUMN_NAME_VECTOR.size();
   private JTable table = new JTable();
   private Random rand = new Random();

   public TableFoo() {
      table.setFillsViewportHeight(true);
      table.setForeground(Color.WHITE);
      table.setBackground(Color.BLACK);

      JButton changeData = new JButton(new ChangeDataAction());
      JPanel southPanel = new JPanel();
      southPanel.setBackground(Color.black);
      southPanel.add(changeData);

      setLayout(new BorderLayout());
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(southPanel, BorderLayout.PAGE_END);
   }

   public void changeTableData() {
      Vector<Vector<String>> matrix = new Vector<Vector<String>>();

      int rowCount = rand.nextInt(5) + 3;
      for (int i = 0; i < rowCount ; i++) {
         Vector<String> row = new Vector<String>();
         for (int j = 0; j < COLUMN_COUNT; j++) {
            String rowText = String.format("row %d col %d:   %d", i, j, rand.nextInt(100));
            row.add(rowText );
         }
         matrix.add(row);
      }

      DefaultTableModel model = new DefaultTableModel(matrix,
            COLUMN_NAME_VECTOR);

      table.setModel(model);
   }

   private class ChangeDataAction extends AbstractAction {
      public ChangeDataAction() {
         super("Change Action");
      }

      public void actionPerformed(java.awt.event.ActionEvent arg0) {
         changeTableData();
      };
   }

   private static void createAndShowGui() {
      TableFoo mainPanel = new TableFoo();

      JFrame frame = new JFrame("TableFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
于 2012-07-22T18:41:22.783 回答
1

最简单的方法是使用 TableModel。

DefaultTableModel model = (DefaultTableModel) this.yourTable.getModel();
model.setRowCount(0);

祝你好运!

于 2013-11-03T01:14:19.533 回答
1

for (int i = model.getRowCount() - 1; i > -1; i--) {

  • 然后添加新元素到XxxTableModel
于 2012-07-22T18:46:58.627 回答