Search code examples
javaswingjtablelayout-managerpreferredsize

How to make a JTable fill entire available space?


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) ?

Screenshot 1

Screenshot 2


Solution

  • 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());