我对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);
以下是该计划目前的样子。 您可以看到这些数字离开屏幕:
非常感谢任何帮助!谢谢。
答案 0 :(得分: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 );
上面的代码会将面板添加到滚动窗格的“视口”中。