user3562926
user3562926

Reputation: 77

How to remove multiple columns from Jtable in Java?

I need to remove 2 columns from a JTable.

If I do:

try { 
jTable5.setModel(dtm);
jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));
jTable5.removeColumn(jTable5.getColumnModel().getColumn(6));
jTable5.setVisible(true);
} 
catch (Exception e){
JOptionPane.showMessageDialog(rootPane, "Error");
}

Then "Error" is displayed.

But, If I do:

try { 
jTable5.setModel(dtm);
jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));
jTable5.setVisible(true);
} 
catch (Exception e){
JOptionPane.showMessageDialog(rootPane, "Error");
}

The error is not displayed, and the table is set to be visible correctly. It seems that I cant remove two columns from a model, using the removeColumn() method twice.

I have noticed, that there is a removeColumnSelectionInterval(), should I use this one?

Any ideas?

Upvotes: 0

Views: 850

Answers (2)

Roman C
Roman C

Reputation: 1

I assume you have 7 columns and removing them by the index. When removed the index count -1, then you can't use an index value higher than size. Change to

jTable5.removeColumn(jTable5.getColumnModel().getColumn(6));
jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));

Upvotes: 2

Yazan
Yazan

Reputation: 6082

first, you should make use of the exception, don't just show "error", show e.getMessage(),

try { 
jTable5.setModel(dtm);
jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));
jTable5.removeColumn(jTable5.getColumnModel().getColumn(6));
jTable5.setVisible(true);
} 
catch (Exception e){
JOptionPane.showMessageDialog(rootPane, "Error " + e.getMessage());
e.printStackTrace();//shows more detailed stack trace
}

and use e.printStackTrace()...

2nd, i think when u are removing the first column, then the other columns get shifted, so when you remove column 5, then there is no column 6 because it was shifted and its 5 too now, thats what cause the error,

so a wild guess is to use

jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));
jTable5.removeColumn(jTable5.getColumnModel().getColumn(5));

yes, remove 5 twice.

Upvotes: 2

Related Questions