问题
I want to created a panel with a table, which fills the entire available space.
I do this using following code:
public class MyFrame extends JFrame {
public EconomyFrame() throws HeadlessException {
super("...");
final JTabbedPane tabbedPane = new JTabbedPane();
add(tabbedPane);
final JPanel companiesPanel = new JPanel();
final CompaniesTableModel companiesModel = new CompaniesTableModel
(ApplicationStateSingleton.INSTANCE.getPersistence().getCompanies());
final JTable companiesTable = new JTable(companiesModel);
ApplicationStateSingleton.INSTANCE.getEventBus().subscribeToPropertyChanges(companiesModel);
companiesPanel.add(new JScrollPane(companiesTable));
tabbedPane.addTab("Companies", companiesPanel);
}
}
But it doesn't work because when I resize the frame, the table fills only part of the available space (see screenshots below).
How can I fix (make the table fill the entire available space) ?
回答1:
Use a layout manager that allows the JTable
occupy the full area available rather than the default FlowLayout
used by JPanel
which only uses its components preferred sizes
JPanel companiesPanel = new JPanel(new GridLayout());
回答2:
There are two issues:
1) first you need to use an appropriate layout manager to make sure that the scrollpane can resize to fill the available area. Typically people would add the scrollpane to the CENTER of a BorderLayout.
2) you need to let the table fill the available space in the viewport of the scrollpane. To do this you use:
table.setFillsViewportHeight(true);
来源:https://stackoverflow.com/questions/19467217/how-to-make-a-jtable-fill-entire-available-space