Reputation: 705
I have a really hard design problem in my swing application. Generally Speaking, I have a JTable
and a JLabel
to display. The label is right below the table.
Is this design Possible?
Upvotes: 1
Views: 1519
Reputation: 2976
Swing layout don't automatically re-layout when a preferred size changes, you'll have to call revalidate (best probably with a TableModelListener which checks if the row count has changed). You also need a layout which sizes the component according to its preferred size, BorderLayout does that for the component in the borders (but not for the one in the center. For a different manager you'll need GridBag or better Mig-/Form- or Table (third party) Layout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TestTableLayout {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(400, 400));
final DefaultTableModel model = new DefaultTableModel(0, 1);
JTable table = new JTable(model) {
@Override
public Dimension getPreferredScrollableViewportSize() {
// view port size should be the same as the preferred size
// limited to the height threshold
Dimension size = super.getPreferredSize();
size.height = Math.min(size.height, 100);
return size;
}
};
new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[] { "Extra row!" });
// trigger a relayout of the panel
panel.revalidate();
panel.repaint();
}
}).start();
panel.add(new JScrollPane(table), BorderLayout.PAGE_START);
JLabel label = new JLabel("my label");
label.setVerticalAlignment(JLabel.TOP);
panel.add(label, BorderLayout.CENTER);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Upvotes: 1
Reputation: 36601
This is certainly possible. Put your JTable
in a JScrollPane
where you set the preferred size of the scroll pane.
And use a LayoutManager
which allows to put those 2 components underneath each other (e.g. a BorderLayout
). So in pseudo-code
JPanel container = new JPanel( new BorderLayout() );
JTable table=...;
JScrollPane scroll = new JScrollPane( table );
scroll.setPreferredSize( xxx, xxx );
container.add( scroll, BorderLayout.CENTER );
container.add( new JLabel( "my label" ), BorderLayout.SOUTH );
If needed, you can adjust the scroll bar policy of the scroll pane
Upvotes: 1