你如何清空JTable?

时间:2012-07-22 18:31:30

标签: java swing jtable

我正在尝试动态地向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");

仅在按钮上按两次或更多次后才会出现此问题。任何人都可以帮我如何动态清空表并在其中添加新数据吗?

编辑: 这是错误日志:

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)

3 个答案:

答案 0 :(得分:3)

要更改JTable的内容,请不要重新创建JTable。只需为它创建一个新的TableModel,例如DefaultTableModel对象或AbstractTableModel扩展类对象,并通过setModel()使用新模型设置表的模型。

此外,您应该避免使用null布局,除非您更改GUI的外观,否则不应该调用updateUI。

例如,

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

答案 1 :(得分:1)

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

  • 然后将新元素添加到XxxTableModel

答案 2 :(得分:1)

最简单的方法是使用TableModel。

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

祝你好运!