user3507930
user3507930

Reputation: 1

JTable error: java.lang.ArrayIndexOutOfBoundsException: 1 >= 0

I created a JTable in Java Swing.

How do I update it so that it displays all the values stored in my MySQL database?

I tried searching on the web, but still no luck.

This is my code...

    try{
        PreparedStatement ps = con.prepareStatement("SELECT * FROM Users ");
        ResultSet result = ps.executeQuery();
        while(result.next()){
            salesTable.setValueAt(result.getString("users"), 1, 1);
        }
    }
    catch(SQLException sqle){
        sqle.printStackTrace();
    }

I keep getting the java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 error.

I would greatly appreciate it if someone could tell me where I am going wrong and a possible fix for this bug.

Upvotes: 0

Views: 366

Answers (3)

LUIS FELIPE
LUIS FELIPE

Reputation: 1

In the beginning, where you would clean and fill your jTable, place this:

dtm.setRowCount(0);

Where dtm is your model in regards to jTable. What this does is clean your model prior each fill.

Upvotes: 0

camickr
camickr

Reputation: 324088

salesTable.setValueAt(result.getString("users"), 1, 1);

I'm guessing you have an empty TableModel.

You can't just use the setValueAt(...) method to add data to a TableModel. The setValueAt(...) method is used to UPDATE existing data in the model. This means the row and column must already exist in the TableModel.

To add new data to the TableModel you need to use the addRow(...) method of the DefaultTableModel.

See the Table From Database Example.java code from Table From Database. It will give you and example of how to dynamically load a TableModel from a ResultSet.

Upvotes: 2

peter.petrov
peter.petrov

Reputation: 39437

This method call
result.getString(name)
expects the name of a column, not the name of a table.

Probably that's where your confusion comes from.

You need to loop through all your column
names and call this method for each one.

Also, the ArrayIndexOutOfBoundsException
comes from the salesTable not from the ResultSet.

Review these two items and you should be able to fix this.

Upvotes: 4

Related Questions