0

I'm aware there are several questions with the same title, and I've tried their answers but to no avail.

I'm getting the following result with my code:

enter image description here

It does not scroll as it should, and there's this empty little space to the right.

Here is the main code for the frame, mainpanel, list panel and the buttons panel that are inside the mainpanel.

public Tester2() {
        JPanel mainPanel = new JPanel(); /////// MAIN PANEL
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setPreferredSize(new Dimension(200, 400));

        JPanel upperListPnl = new JPanel(); ////// LIST PANEL
        upperPnlSetup(upperListPnl);

        JPanel lowerBtnsPnl = new JPanel(); ///// BUTTONS PANEL
        lowerBtnsPnl.setLayout(new BorderLayout());
        JButton testButton = new JButton("Test the list");
        testButton.addActionListener(e -> {
            exampleModel.addElement("List has been tested");
            updateExampleData();
        });
        lowerBtnsPnl.add(testButton);

        mainPanel.add(upperListPnl, BorderLayout.CENTER);
        mainPanel.add(lowerBtnsPnl, BorderLayout.SOUTH);

        JFrame frame = new JFrame();
        frame.add(mainPanel);
        frame.setVisible(true);
        frame.pack();
        frame.setLocationRelativeTo(null);
    }

Here is the code for the JList and the JScrollpane (upper panel):

public void upperPnlSetup(JPanel panel) {
        panel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        exampleList = new JList<>(exampleModel);

        JScrollPane jsp = new JScrollPane(exampleList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        c.fill = GridBagConstraints.BOTH;
        c.weighty = 1;
        c.weightx = 0.75;
        panel.add(exampleList, c);

        c.weightx = 0.25;
        panel.add(jsp, c);
    }

And then the JList and model list as well as the data updating method:

private JList<String> exampleList;
private DefaultListModel<String> exampleModel = new DefaultListModel<>();

public void updateExampleData() {
        exampleList.setModel(exampleModel);
    }

I tried a FloatLayout, a BorderLayout, and a GridLayout (0,2 and 0,1) all of which didn't work. Finally, I settled for the GridBagLayout since it's seemingly always used for JLists and/or JScrollpanes, and I played with the GridBagConstraints as well as the positioning of the code but seem to always land on the same problem. I've tried giving the scroll pane a preferredSize, didn't do anything.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
toxette
  • 13
  • 5

1 Answers1

0

Okay so, apparently the problem was that I was adding the list to the panel. Adding it to the scrollpane, then adding the scrollpane to the panel was enough, so commenting out the

panel.add(exampleList, c);`

fixed the whole thing.

toxette
  • 13
  • 5