【问题标题】:JScrollPane doesn't seem to scrollJScrollPane 似乎没有滚动
【发布时间】:2017-08-20 07:56:05
【问题描述】:

我对 Java Swing 还是很陌生。有人可以帮我弄清楚我做错了什么吗?请在任何必要的地方纠正我。这段代码的很大一部分是反复试验。

我有一个框架,其中包含一个 JPanel。 JPanel 使用“GridBag”布局。如图所示,包含的代码围绕右侧的子 JPanel 旋转。出于某种原因,我的垂直滚动条似乎无法正常工作。

这是感兴趣的代码:

/// GridBagConstraints
GridBagConstraints gbc = new GridBagConstraints();

// parent jpanel for scrollpane
scrollPanel = new JPanel();
scrollPanel.setLayout(new BorderLayout());
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
add(scrollPanel, gbc);

// content jpanel for scrollpane
scrollPaneContent = new JPanel();
scrollPaneContent.setLayout(new GridLayout(0, 1, 0, 1));

// scrollPane
scrollPane = new JScrollPane();
scrollPane.setBorder(BorderFactory.createEmptyBorder(0,30,0,0));
scrollPane.setViewportView(scrollPaneContent);
scrollPanel.add(scrollPane, BorderLayout.PAGE_START);

这是程序目前的样子。 你可以看到刚刚离开屏幕的数字:

非常感谢任何帮助!谢谢。

【问题讨论】:

标签: java swing jscrollpane


【解决方案1】:
scrollPanel.add(scrollPane, BorderLayout.PAGE_START);

您正在尝试将 scrollPane 添加到 scrollPanel。这不是它的工作方式。

JScrollPane 是一个容器,所以需要将包含组件的面板添加到滚动窗格中

JPanel panel = new JPanel(...);
panel.add(....);
panel.add(....);
JScrollPane scrollPane = new JScrollPane( panel );
frame.add( scrollPane );

上面的代码会将面板添加到滚动窗格的“视口”中。

【讨论】:

  • 我将 scrollPane 添加到 scrollPanel,并使用 scrollPaneContent 作为 JScrollPane 的视口,如下所示:scrollPane.setViewportView(scrollPaneContent);。这是不正确的吗?谢谢。
  • @gab64, Is this incorrect? - 我已经告诉过你这是不正确的,并向你展示了正确的方法。
  • 我明白了。我现在以正确的方式工作,谢谢。作为替代方案,我发现它也适用于:setMinimumSize 和 setPreferredSize,但是我试图避免对大小进行硬编码。再次感谢!
  • @gab64, As an alternative... - 不,这不是替代方案。每个组件可以在不同的外观和感觉上具有不同的尺寸。让布局管理器动态确定首选大小。您设置的任何尺寸都只是随机猜测。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2017-10-24
  • 2017-11-11
  • 1970-01-01
  • 2012-11-08
  • 2015-06-11
相关资源
最近更新 更多