user1760166
user1760166

Reputation: 99

How to show/hide certain JTable columns based on selection in JComboBox

I have a JTable and a JComboBox. I want certain columns to hide when I select one item in the combobox and the same hidden columns to reappear when I select the other item in the combobox. I write,

jTable1.getColumnModel().getColumn(8).setMinWidth(0)
jTable1.getColumnModel().getColumn(8).setMaxWidth(0)
jTable1.getColumnModel().getColumn(8).setWidth(0)

for hiding the column, but when I again write

jTable1.getColumnModel().getColumn(8).setMinWidth(100)
jTable1.getColumnModel().getColumn(8).setMaxWidth(100)
jTable1.getColumnModel().getColumn(8).setWidth(100)

the hidden columns do not become visible.

Upvotes: 1

Views: 1349

Answers (4)

trashgod
trashgod

Reputation: 205795

what's a problem in above code?

In addition to kleopatra's helpful insight, documented here, some L&Fs are more or less cooperative. For example, com.apple.laf.AquaLookAndFeel always leaves enough width to drag after setMinWidth(0), although the column can be forced to zero width manually.

Upvotes: 1

Robin
Robin

Reputation: 36611

Use JTable#removeColumn and JTable#addColumn. These operations only affect the view side, not the model side

Upvotes: 1

kleopatra
kleopatra

Reputation: 51525

Reason is that both setMin/setMax enforce the relation

min <= width <= max

That is the order of method calling matters

// hiding
column.setMinWidth(0);
column.setMaxWidth(0);

// showing
column.setMaxWidth(100);
column.setMinWidth(100);

Note that you need not call setWidth, that's handled internally.

That said: forcing the sizes is .. a hack. Consider using a clean solution, f.i. a framework like SwingX which has (amongst other niceties :-) full-fledged support for column hiding

Upvotes: 1

user1760166
user1760166

Reputation: 99

for (int i = 0; i < 2; i++) {
    jTable1.getColumnModel().getColumn(8).setMinWidth(100)
    jTable1.getColumnModel().getColumn(8).setMaxWidth(100)
    jTable1.getColumnModel().getColumn(8).setWidth(100)
}

The columns will become visible.

Upvotes: 0

Related Questions