When I call setAutoResizeMode
with AUTO_RESIZE_OFF
and AUTO_RESIZE_ALL_COLUMNS
, then I get expected results described here when I resize the window.
When I call it with AUTO_RESIZE_LAST_COLUMN
, then I get behavior exactly as if I specified AUTO_RESIZE_ALL_COLUMNS
.
Why?
Here's the MCV example:
import javax.swing.*;
import java.awt.*;
public class ScrollableJTable extends JPanel {
public ScrollableJTable() {
setLayout(new BorderLayout());
JTable table = new JTable(10, 10);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); // vary the constant
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel panel = new ScrollableJTable();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
$ javac -version
javac 1.8.0_221
$ java -version
java version "1.8.0_221"
Java(TM) SE Runtime Environment (build 1.8.0_221-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)
# compile && go
$ javac ScrollableJTable.java && java ScrollableJTable
It seems that the JTable
auto-resize mode only applies when a single column changed its own size and not the entire table. As per JTable.doLayout()
javadoc:
If the
resizingColumn
is notnull
, it is one of the columns in the table that has changed size rather than the table itself. In this case the auto-resize modes govern the way the extra (or deficit) space is distributed amongst the available columns.
You can see this behavior by setting the column manually with JTableHeader.setResizingColumn()
with following code, it will auto-resize the last column:
JTableHeader header = table.getTableHeader();
TableColumn lastColumn = header.getColumnModel().getColumn(9);
header.setResizingColumn(lastColumn);
Not sure if this is a bug or intended behavior. It could be bug JDK-4098154. A clue that it's a bug is revealed in the setResizingColumn
javadoc:
Application code will not use this method explicitly, it is used internally by the column sizing mechanism.
They could have just as easily (and accurately) wrote this:
If the only way you can make your code work is to use this method then our code has a bug.
Make the number of columns 5 (to make the behaviour more apparent) and then resize the frame larger.
In both cases the columns will resize equally.
Next try resizing an individual column.
In this case you will see the different behaviour when using AUTO_RESIZE_LAST_COLUMN
and AUTO_RESIZE_ALL_COLUMNS
.
I would guess the answer to your question is that the resize mode is only applicable to individual column resizing, not resizing of the entire table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With