How to make a JTable fill entire available space?

三世轮回 提交于 2020-01-06 13:56:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!