问题描述
我有一个 JScrollPane
,它将填充用户添加的按钮。当前,用户创建一个新按钮,并将其添加到滚动窗格内的容器中,但不显示任何内容。
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?
启动滚动窗格和容器:
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);
向容器中添加新的 JButton
组件:
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;
推荐答案
scrollPane.add(contractContainer);
不要在JScrollPane中添加组件。该组件需要添加到scollpane的视口
中。可以通过以下两种方法之一完成此操作:
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 );
或
scrollPane = new JScrollPane();
scrollPane.setViewportView( contractContainer );
除非您在视口中动态更改组件,否则我将使用第一种方法。
I would use the first way unless you dynamically change the component in the viewport.
然后,当您将组件添加到可见gui时,代码将是:
Then when you add a component to the visible gui the code would be:
contractContainer.add(a);
contractContainer.revalidate();
contractContainer.repaint();
这篇关于容器未显示在JScrollPane中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!