Search code examples
javaswingjscrollpanegrid-layoutjscrollbar

Java, GirdLayout, ScrollPane not working


I have Two JTables, every JTables is added to a Container with a Borderlayout (the TableHeader to BoderLayout.PAGE_START and the JTable to the Center) these Container are added to a JScrollPane.

The Two Container are added to a Container with a Gridlayout, which is added to the Center of the JPanel.

The Problem is, that the scrollBar is not showing or if a force the scrollbar to Display all the time, it is not working. The JTable has over 100 entries but only the first ~30 entries are shown.

I already tried searching and found already some possible fixes, but they didn't work. I have tried it with a prefered Size, added a Layout to the ScrollPane and some other possibilties, but nothing worked.

Some code of the Jtable:

        this.locations = new JTable(data, columnNames);
        this.locations.getTableHeader().setReorderingAllowed(false);
        this.locations.setDefaultEditor(Object.class, null);
//      this.locations.setPreferredSize(new Dimension(100, 100));

        Container table = new Container();
        table.setLayout(new BorderLayout());
        table.add(this.locations.getTableHeader(), BorderLayout.PAGE_START);
        table.add(this.locations, BorderLayout.CENTER);

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        this.content.add(scrollPane);

Locations is the JTable, Content is the Container with the Gridlayout, which is then added to the JPanel with the BorderLayout.


Solution

  •     Container table = new Container();
        table.setLayout(new BorderLayout());
        table.add(this.locations.getTableHeader(), BorderLayout.PAGE_START);
        table.add(this.locations, BorderLayout.CENTER);
    

    There is no need for the above code.

    All you need is:

        this.locations = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        this.content.add(scrollPane);