java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 尝试填充 JTable

发布于 2024-08-11 03:24:57 字数 5370 浏览 3 评论 0原文

我对 JTable 进行子类化并使用 DefaultTableModel 来对表数据进行建模。以下类设置 JTable,并向模型添加一行。

import java.io.File;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JTable;  
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class SelectedFileTable extends JTable {
Vector<File> SelectedFiles = new Vector<File>(); 
DefaultTableModel Model    = new DefaultTableModel();

TableColumn ColumnName     = new TableColumn();
TableColumn ColumnSize     = new TableColumn();
TableColumn ColumnRmIcon   = new TableColumn(); 

ImageFilenameFilter Filter = new ImageFilenameFilter();

public SelectedFileTable() {
    super();
    this.setModel(Model);

    ColumnName.setHeaderValue(new String("Name") );
      ColumnName.setMinWidth(200);
    ColumnSize.setHeaderValue(new String("Size") );
      ColumnSize.setMinWidth(50); 
      ColumnSize.setMaxWidth(100);
    ColumnRmIcon.setHeaderValue(new String("Remove?") );
      ColumnRmIcon.setMaxWidth(100);
      ColumnRmIcon.setResizable(false);

    this.addColumn(ColumnName);
    this.addColumn(ColumnSize);
    this.addColumn(ColumnRmIcon);

    this.setShowVerticalLines(false);
    this.setShowHorizontalLines(true);
this.setAutoCreateColumnsFromModel(true);

this.addFile( new File("C:/temp/cfk.jpg") );
}
public void addFile(File file) {
    System.out.println("FileTable adding: " + file.getName() );
    if ( file.isDirectory() ) { 
        for ( File f : file.listFiles(Filter) ) {
            this.addFile(f);
        }
    } else { 
        if ( Filter.accept(file) ) {
            System.out.println("Accepting file; " + file.getName() );
            SelectedFiles.add(file);
            {
                String name = file.getName();
                Long size = new Long( file.length() );
                String tempstr = new String("X");

                System.out.println("RowItems before: " + Integer.toString(Model.getRowCount()) );
                Model.addRow( new Object[] { name, size, tempstr } );
                Model.fireTableDataChanged(); 
                System.out.println("RowItems start : " + Integer.toString(Model.getRowCount()) );
            }
            System.out.println("Done Accepting file; " + file.getName() );
        }
    }
}
public Iterator<File> iterator() { 
    return SelectedFiles.iterator();
}

}

在显示/可视化时,会引发以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:432)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:622)
at javax.swing.JTable.getValueAt(JTable.java:1903)
at javax.swing.JTable.prepareRenderer(JTable.java:3911)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1897)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:743)
at javax.swing.JComponent.paint(JComponent.java:1006)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4979)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4925)
at javax.swing.JComponent.paint(JComponent.java:996)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1709)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
at sun.awt.RepaintArea.paint(RepaintArea.java:224)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
at java.awt.Component.dispatchEventImpl(Component.java:4060)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

我正在抓狂 - 我无法找到这个极其简单的用例的根本原因。

I'm subclassing JTable and using a DefaultTableModel to model my table data. The following class sets up the JTable, and adds one row to the model.

import java.io.File;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.JTable;  
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class SelectedFileTable extends JTable {
Vector<File> SelectedFiles = new Vector<File>(); 
DefaultTableModel Model    = new DefaultTableModel();

TableColumn ColumnName     = new TableColumn();
TableColumn ColumnSize     = new TableColumn();
TableColumn ColumnRmIcon   = new TableColumn(); 

ImageFilenameFilter Filter = new ImageFilenameFilter();

public SelectedFileTable() {
    super();
    this.setModel(Model);

    ColumnName.setHeaderValue(new String("Name") );
      ColumnName.setMinWidth(200);
    ColumnSize.setHeaderValue(new String("Size") );
      ColumnSize.setMinWidth(50); 
      ColumnSize.setMaxWidth(100);
    ColumnRmIcon.setHeaderValue(new String("Remove?") );
      ColumnRmIcon.setMaxWidth(100);
      ColumnRmIcon.setResizable(false);

    this.addColumn(ColumnName);
    this.addColumn(ColumnSize);
    this.addColumn(ColumnRmIcon);

    this.setShowVerticalLines(false);
    this.setShowHorizontalLines(true);
this.setAutoCreateColumnsFromModel(true);

this.addFile( new File("C:/temp/cfk.jpg") );
}
public void addFile(File file) {
    System.out.println("FileTable adding: " + file.getName() );
    if ( file.isDirectory() ) { 
        for ( File f : file.listFiles(Filter) ) {
            this.addFile(f);
        }
    } else { 
        if ( Filter.accept(file) ) {
            System.out.println("Accepting file; " + file.getName() );
            SelectedFiles.add(file);
            {
                String name = file.getName();
                Long size = new Long( file.length() );
                String tempstr = new String("X");

                System.out.println("RowItems before: " + Integer.toString(Model.getRowCount()) );
                Model.addRow( new Object[] { name, size, tempstr } );
                Model.fireTableDataChanged(); 
                System.out.println("RowItems start : " + Integer.toString(Model.getRowCount()) );
            }
            System.out.println("Done Accepting file; " + file.getName() );
        }
    }
}
public Iterator<File> iterator() { 
    return SelectedFiles.iterator();
}

}

At display/visualization time, the following exception is thrown:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:432)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:622)
at javax.swing.JTable.getValueAt(JTable.java:1903)
at javax.swing.JTable.prepareRenderer(JTable.java:3911)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1897)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:743)
at javax.swing.JComponent.paint(JComponent.java:1006)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paint(JComponent.java:1015)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:843)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4979)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4925)
at javax.swing.JComponent.paint(JComponent.java:996)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1709)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
at sun.awt.RepaintArea.paint(RepaintArea.java:224)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
at java.awt.Component.dispatchEventImpl(Component.java:4060)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

I'm ripping my hair out - I haven't been able to find the root cause of this immensely simple use case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

被翻牌 2024-08-18 03:24:57

我也讨论过这个问题(使用 JList 和 DefaultListModel)。
德米特里的回答是正确的。

然而,还有一件事:
如果您不在 Swing 的事件调度线程中修改模型,也可能会抛出此异常。

执行以下操作可以帮助您避免此异常:

SwingUtilities.invokeLater(new Runnable(){public void run(){
    //Update the model here
}});

http:// www.javakb.com/Uwe/Forum.aspx/java-gui/3012/JList-JScrollPane-DefaultListModel-Updating

I ran on this issue too (with a JList and a DefaultListModel).
Dmitry's answer is right.

However, there is another thing:
this exception can also be thrown if you don't modify the model in Swing's Event Dispatch Thread.

Doing the following can help you avoid this exception:

SwingUtilities.invokeLater(new Runnable(){public void run(){
    //Update the model here
}});

http://www.javakb.com/Uwe/Forum.aspx/java-gui/3012/JList-JScrollPane-DefaultListModel-Updating

会发光的星星闪亮亮i 2024-08-18 03:24:57

我认为您需要向 TableModel 添加列。您的代码将 UI 列添加到表中,但不将它们添加到模型中

I think you need to add columns to your TableModel. Your code adds UI columns to the table but doesn't add them to the model

左耳近心 2024-08-18 03:24:57

德米特里是对的。替换

this.addColumn(ColumnName);
this.addColumn(ColumnSize);
this.addColumn(ColumnRmIcon);

Model.addColumn(ColumnName);
Model.addColumn(ColumnSize);
Model.addColumn(ColumnRmIcon);

,现在模型知道了列,并且当您尝试向认为有 0 列的模型添加行时,不再抛出异常

Dmitry is right. Replace

this.addColumn(ColumnName);
this.addColumn(ColumnSize);
this.addColumn(ColumnRmIcon);

with

Model.addColumn(ColumnName);
Model.addColumn(ColumnSize);
Model.addColumn(ColumnRmIcon);

and now the Model knows about the columsn and won't throw an Exception anymore when you try to add a row to a model which thinks it has 0 columns

芯好空 2024-08-18 03:24:57

来自 JTable.setAutoCreateColumnsFromModel() API:

“如果 autoCreateColumnsFromModel 从 false 更改为 true,则此方法调用 createDefaultColumnsFromModel。”

Vector 抛出 ArrayIndexOutOfBoundsException - 如果索引超出范围 (index < 0 || index >= size())

I根据 Dmitry 的建议,猜测表模型缺少列

From the JTable.setAutoCreateColumnsFromModel() API:

"This method calls createDefaultColumnsFromModel if autoCreateColumnsFromModel changes from false to true. "

Vector throws ArrayIndexOutOfBoundsException - if the index is out of range ( index < 0 || index >= size())

I guess the table model is missing the columns, as suggested by Dmitry

柳絮泡泡 2024-08-18 03:24:57

将您的代码替换为以下内容
在这里,您只需要删除应该对所有行进行迭代的第一行

private void refreshTable() {

   int rowCount= model.getRowCount();

  // System.out.println(rowCount);

   for(int i=0;i<rowCount;i++ ){
        model.removeRow(0);
        //System.out.println(i);
   }

}

Replace your code with the following
Here you need to remove first row only that should be iterated for all the rows

private void refreshTable() {

   int rowCount= model.getRowCount();

  // System.out.println(rowCount);

   for(int i=0;i<rowCount;i++ ){
        model.removeRow(0);
        //System.out.println(i);
   }

}
翻了热茶 2024-08-18 03:24:57

替换

tabWindow.addTab(...);

SwingUtilities.invokeLater(new Runnable() {
    @Override public void run() {
        tabWindow.addTab(...);
    }
});

当您更改操作侦听器中的选项卡式窗格时,可能会发生这种情况。

replace

tabWindow.addTab(...);

with

SwingUtilities.invokeLater(new Runnable() {
    @Override public void run() {
        tabWindow.addTab(...);
    }
});

Such situation can hapen when you change tabbed pane in action listener.

悍妇囚夫 2024-08-18 03:24:57

当您使用 RowSorter 时,另一个问题可能会相关。当您编辑模型时,RowSorter 尝试对旧模型重新排序。它应该在表模型的每次更改时自动重新创建并重新运行。

修复它

tableModel = new DefaultTableModel(data, columnNames);
jTableSentence.setModel(tableModel);
jTableSentence.setRowSorter(new TableRowSorter(tableModel));
jTableSentence.setAutoCreateRowSorter(true);

你可以通过-Hayri

Another issue might be related when you use RowSorter. When you edit the model RowSorter tries to re-sort the old model. It should be automatically re-created and re-run on each changes of table model.

You can fix it by

tableModel = new DefaultTableModel(data, columnNames);
jTableSentence.setModel(tableModel);
jTableSentence.setRowSorter(new TableRowSorter(tableModel));
jTableSentence.setAutoCreateRowSorter(true);

-Hayri

南城追梦 2024-08-18 03:24:57

我遇到这个问题是因为我将列和行添加到 JTable 而不是模型中。

最好的办法是这个。

Object[][]rows = new Object[ ][ ] { {"a","b"} , {"c","d"} };
Object[]columns = new Object[] {"column1","column2"};
JTable table = new JTable();
table.setModel(new DefaultTableModel(rows,columns));

I was facing this problem because i was adding columns and rows to the JTable not to the model.

best way is this.

Object[][]rows = new Object[ ][ ] { {"a","b"} , {"c","d"} };
Object[]columns = new Object[] {"column1","column2"};
JTable table = new JTable();
table.setModel(new DefaultTableModel(rows,columns));
染年凉城似染瑾 2024-08-18 03:24:57

德米特里是对的,但你只需要更新你的模型。
为此,请将以下内容添加到您的代码中:

DefaultTableModel dtm = (DefaultTableModel) table.getModel();
for (int c = 0; c < table.getColumnCount(); c++) {
dtm.addColumn(table.getColumnName(c));
}

Dmitry is right, but you simply have to update your model.
To do this, add the following to your code:

DefaultTableModel dtm = (DefaultTableModel) table.getModel();
for (int c = 0; c < table.getColumnCount(); c++) {
dtm.addColumn(table.getColumnName(c));
}
不如归去 2024-08-18 03:24:57

有必要将 isCellEditable 方法添加到您的表模型类中并返回 false。

@Override
  public boolean isCellEditable(int row, int column)
  {
    return false;
  }

It is necessary to add isCellEditable method to your table model class with return false.

@Override
  public boolean isCellEditable(int row, int column)
  {
    return false;
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文