Re: JTable, JScrollPane and empty space
In article <IdydnSRiIqV1LpHSnZ2dnUVZ_v2dnZ2d@megapath.net>,
"A. W. Dunstan" <no@spam.thanks> wrote:
I'd be more than happy to switch to some other layout manager if
that's needed.
One approach is to use BoxLayout: use setPreferredScrollableViewportSize
as desired and restrict the maximum size of the smaller table's scroll
pane.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class TablePanel extends JPanel {
public static final int WIDE = 300;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("TablePanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new TablePanel());
f.pack();
f.setVisible(true);
}
});
}
public TablePanel() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JTable tableA = new JTable(new MyModel("A", 12));
int h = tableA.getPreferredSize().height;
tableA.setPreferredScrollableViewportSize(
new Dimension(WIDE, h));
JScrollPane jspA = new JScrollPane(tableA);
jspA.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jspA.setMaximumSize(new Dimension(Short.MAX_VALUE, h));
this.add(jspA);
JTable tableB = new JTable(new MyModel("B", 32));
h = tableB.getPreferredSize().height;
tableB.setPreferredScrollableViewportSize(
new Dimension(WIDE, h / 2));
final JScrollPane jspB = new JScrollPane(tableB);
jspB.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.add(jspB);
}
private static class MyModel extends AbstractTableModel {
private final String name;
private final int rows;
public MyModel(String name, int rows) {
this.name = name;
this.rows = rows;
}
@Override
public int getRowCount() {
return rows;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int col) {
return name + (col + 1);
}
@Override
public Object getValueAt(int row, int col) {
return (row + 1) / 10.0;
}
@Override
public Class<?> getColumnClass(int col) {
return Number.class;
}
}
}
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>