Reputation: 12313
When changing the preferred size of a JTable inside a JScrollPane, the JScrollPane doesn't update its scrollbars appropriately even though the AS_NEEDED
policy is set for both vertical and horizontal scrollbars. How do I get the scroll pane to update its scrollbars?
The code below will show that the JTable's preferred size changes but the JScrollPane doesn't ever add scrollbars.
Here's my SSCCE... although the "correct" part is in question:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class jTableResizeWidthInScrollPane {
public static void main( String[] args ) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
JTable table = new JTable();
final TimesTableModel timesTableModel = new TimesTableModel();
JTextField textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent ae ) {
timesTableModel.setMaxNumber(Integer.parseInt(textField.getText()));
SwingUtilities.invokeLater( new Runnable() {
public void run() {
table.revalidate();
System.out.println(
"preferred width: "+
table.getPreferredSize().getWidth()
);
}
});
}
});
table.setModel(timesTableModel);
scrollPane.setViewportView(table);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.setLayout(new BorderLayout());
frame.add(textField,BorderLayout.NORTH);
frame.add(table,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static class TimesTableModel extends AbstractTableModel {
private int max = 10;
public int getRowCount() {
return max;
}
public int getColumnCount() {
return max;
}
public void setMaxNumber( int max ) {
this.max = max;
fireTableStructureChanged();
}
public Object getValueAt(int row, int col) {
return (row+1)*(col+1);
}
@Override
public String getColumnName(int col) {
return String.valueOf(col);
}
}
}
Upvotes: 0
Views: 78
Reputation: 347314
Two things
JTable
to your frame when you should be adding the JScrollPane
setAutoResizeModel
on the JTable
and setting it to something like AUTO_RESIZE_OFF
Something like...
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
frame.add(scrollPane, BorderLayout.CENTER);
Upvotes: 2