Container not displaying in JScrollPane

馋奶兔 提交于 2020-06-29 03:41:34

问题


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;

回答1:


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


来源:https://stackoverflow.com/questions/62305235/container-not-displaying-in-jscrollpane

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