所以我将这个面板定位在我的框架的顶部(NORTH)侧,称为menupanel。在这个面板里面,我还有另外两个面板--topPanel和botPanel(红色和黑色)。在这两个面板内部有几个按钮(在此示例中为标签)。我想在两个面板(机器人和顶部)上添加滚动(水平)。
{{1}}
答案 0 :(得分:2)
您要将组件添加到多个容器中:
scrollT = new JScrollPane(topPanel); // topPanel added to scroll pane
scrollT.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollB = new JScrollPane(botPanel); // botPanel added to scroll pane
scrollB.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
menupanel.add(scrollT); // scrollpanes added to menupanel -- without Borderlayout constants?
menupanel.add(scrollB);
menupanel.add( topPanel, BorderLayout.NORTH ); // topPanel added to menupanel
menupanel.add( botPanel, BorderLayout.SOUTH );
这不允许用于Swing GUI。
而是将topPanel和botPanel添加到JScrollPanes,将JScrollPanes添加到GUI的其余部分,但不要将topPanel和botPanel重新添加到任何内容。
另一个问题 - 你限制了topPanel和botPanel的大小,这会使它们不能滚动 - 避免这样做。如果您需要约束某些内容的大小,请执行滚动窗格的视口或滚动窗格本身。
如,
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
public class ScrollPaneFun2 extends JPanel {
private static final int PREF_W = 500;
public ScrollPaneFun2() {
JPanel topPanel = new JPanel(new GridLayout(0, 1));
JPanel botPanel = new JPanel(new GridLayout(0, 1));
for (int i = 0; i < 3; i++) {
JPanel innerTopPanel = new JPanel(new GridLayout(1, 0, 3, 0));
JPanel innerBotPanel = new JPanel(new GridLayout(1, 0, 3, 0));
for (int j = 0; j < 50; j++) {
innerTopPanel.add(new JLabel("Text " + (i + 1)));
innerBotPanel.add(new JLabel("Text " + (i + 1)));
}
topPanel.add(innerTopPanel);
botPanel.add(innerBotPanel);
}
JScrollPane topScrollPane = new JScrollPane(topPanel);
JScrollPane botScrollPane = new JScrollPane(botPanel);
topScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
botScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
setLayout(new GridLayout(0, 1));
add(topScrollPane);
add(botScrollPane);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
int height = super.getPreferredSize().height;
return new Dimension(PREF_W, height);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ScrollPaneFun2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ScrollPaneFun2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}