简体   繁体   中英

Java Swing JTable: cannot access the values in the table due to incorrect usage/creation of table model

I am just beginning to program using Java Swing. I am not very familiar with each of the many Java Swing Classes, and have ran into a stumbling block regarding the creation of a Table.

I am trying to figure out how to add a table to a Java Swing Program I am making. I have looked at docs.oracle.com to try and figure it out but I am getting an error when I try to access the values of the table. I will include my code to help show what I am currently trying to do and where the error is.

This is my code for making the table and the table model (I think the problem is that my table model is not working correctly):

        /*Create the Table Entry*/
        columnNames = new String[listoffields.size()+1];
        columnNames[0] = "Record Number";
        for(int a = 1; a < columnNames.length;a++){
            columnNames[a] = listoffields.get(a-1).getTitle();
        }
        int count = 1;
        data = new Object[numrecords][listoffields.size()+1];
        for(int a = 0; a < numrecords;a++){
            for(int b = 0; b < listoffields.size()+1;b++){
                if(b == 0){
                    data[a][b] = count;
                    count++;
                }
                else{
                    data[a][b] = "";
                }
            }
        }

        /* create the table */
        JTable table = new JTable(data,columnNames);
        table.setCellSelectionEnabled(true);
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                return columnNames[col].toString();
            }
            public int getRowCount() { return data.length; }
            public int getColumnCount() { return columnNames.length; }
            public Object getValueAt(int row, int col) {
                return data[row][col];
            }
            public boolean isCellEditable(int row, int col) {
                return (col >= 1);
            }
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
            }
        });
        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);

        /* addthe table to the JTable tableentry*/
        tabelentry.setLayout(new BoxLayout(ProjectFrame.tabelentry, BoxLayout.Y_AXIS));
        tabelentry.add(scrollPane);
        tabelentry.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

After the table is displayed and I edit the blank values for each cell, I click a submit button that submits the cell. However, the following error is encountered:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
   at java.util.Vector.elementAt(Unknown Source)
   at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
   at Client.GUIComponents.ProjectFrame$1.submit(NameOfFile.java:LineNumber)

The error is encountered when trying to submit as follows:

public void submit(){
   String recordvalues = ""; //contains a String representation of what I want to submit
   for(int a = 0; a < numberoffields;a++){
      for(int b = 0; b < numberofrecords;b++){
         if(a != 0){ //I want to skip the first column
            recordvalues = recordvalues  + (String) tabelentry.getModel().getValueAt(b, a) + ","; //The error is at this line in the code
         }
      }
   }
}

I provided my code to give an example of the current problems I am encountering and what I have currently tried. To generalize my question, I am wondering how to correctly write a table model class so that I can access the values at each of the cells in the table. Any assistance would be helpful. Thanks a ton!

My immediate thought is that you're creating two different table models.

JTable table = new JTable(data,columnNames);
table.setCellSelectionEnabled(true);
table.setModel(new AbstractTableModel() {...

new JTable(data,columnNames) is actually creating it's own DefaultTableModel based on the information you are providing it. Try removing the table.setModel(new AbstractTableModel() {... code

The other, associated, problem is, I don't know how data and columnNames are declared.

Have a read through How to Use Tables for more details

Updated

The other problem, as pointed about by Hovercraft, is you adding one table to another and then accessing the wrong model.

The table creation should look more like...

tableEntry = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(tableEntry );
tableEntry .setFillsViewportHeight(true);
// Don't forget to add the scroll pane to you view !!

Then you submit method should look more like...

public void submit(){
    String recordvalues = ""; //contains a String representation of what I want to submit
    TableModel model = tableEntry.getModel();
    for(int a = 0; a < model.getColumnCount();a++){
        for(int b = 0; b < model.getRowCount();b++){
            if(a != 0){ //I want to skip the first column
                recordvalues = recordvalues  + (String) model.getValueAt(b, a) + ","; //The error is at this line in the code
            }
        }
    }
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

This exception means that the column size of your table is 0, I think it's because you don't add columns into your TableModel .

Try to create several TableColumn Column = new TableColumn(); then add these columns to your table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM