Container not displaying in JScrollPane

Tags: , , , ,



I have a JScrollPane that will fill up with buttons added by the user. Currently, the user creates a new button and it is added to the container that is inside the scroll pane but nothing is displayed.

Is this because the scroll pane has already been displayed?

Initiating the scroll pane and container:

newHeading.addActionListener(this);
newHeading.setActionCommand("newHeading");

contractContainer.setLayout(new BoxLayout(contractContainer, BoxLayout.Y_AXIS));

scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.add(contractContainer);

contractHeadingPanel.setLayout(new BorderLayout());
contractHeadingPanel.add(newHeading, BorderLayout.SOUTH);
contractHeadingPanel.add(scrollPane, BorderLayout.CENTER);

contractHeadingFrame.setSize(200, 400);
contractHeadingFrame.setAlwaysOnTop(true);
contractHeadingFrame.add(contractHeadingPanel);
contractHeadingFrame.setVisible(true);

Adding new JButton components to the container:

case "newHeading":
    // Adds new details section
    headingDetails.add(new String[0][0]);
    // Adds title to list
    headingTitles.add(JOptionPane.showInputDialog(this, "Heading title:"));
    // Sets up and adds button to container
    JButton a = new JButton(headingTitles.get(headingTitles.size()-1));
    a.addActionListener(this);
    contractContainer.add(a);
    Log.logLine(this.getClass(), "Adding new Heading under " + a.getText());
    // Adds Heading title to list
    headingTitles.add(a.getText());

    scrollPane.revalidate();
    repaint();
    break;

Answer

scrollPane.add(contractContainer);

Don’t add components to a JScrollPane. The component needs to be added to the viewport of the scollpane. This can be done in one of two ways:

scrollPane = new JScrollPane( contractContainer );

or

scrollPane = new JScrollPane();
scrollPane.setViewportView( contractContainer );

I would use the first way unless you dynamically change the component in the viewport.

Then when you add a component to the visible gui the code would be:

contractContainer.add(a);
contractContainer.revalidate();
contractContainer.repaint();


Source: stackoverflow