1

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
user1760166
  • 89
  • 2
  • 8

4 Answers4

1

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

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • You know I am a fan of `SwingX`, but column hiding is part of the JDK as well. `JTable#removeColumn` removes the column from the view side only, not from the model side – Robin Oct 21 '12 at 10:45
  • @Robin yeah, I know :-) The part that requires some more thought (than hiding) is to show it again at the expected position. Not rocket science of course, but nice-to-have without needing to worry about the boring details. – kleopatra Oct 21 '12 at 10:54
1

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

Robin
  • 36,233
  • 5
  • 47
  • 99
1

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
0
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.

user1760166
  • 89
  • 2
  • 8