首页 > 解决方案 > 尝试在 Jpanel 中添加 ScrollPane,在 BorderLayout 中使用空布局

问题描述

我正在尝试在 jpanel 中添加一个具有空布局的滚动条。

我想创建一个表格。这应该始终在底部显示几个按钮。即使调整父容器的大小,表单内的任何内容都应保持其大小和比例。

这是我带来的。我有一个带有边界布局的面板,并在边界的南部添加了按钮。然后创建另一个 jpanel 以包含添加到父 jpanel 中心的表单。因为我希望表单保持它的比例,所以我使用了内部面板的空布局。但是我希望它在内容不完全可见时显示滚动条。在此处输入图像描述

现在将内部 jpanel 添加到滚动窗格并将滚动面板添加到父面板 (.add(scrollpane, BorderLayout.CENTER)) 不会提供所需的格式。我可以做些什么来获得所需的格式吗?

这是代码示例:

public static void main(String[] args) {
    JFrame jFrame = new JFrame();
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.setSize(new Dimension(1000, 700));
    Container c = jFrame.getContentPane();
    c.setLayout(new BorderLayout());
    bottomPanel(c);
    centerPanel(c); //scrollbar should go in this panel
    jFrame.setVisible(true);
}

private static void centerPanel(Container c) {
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(null);
    JButton button = new JButton("This jObject should not resize when window resizes and also should maintain relative position.");
    button.setBounds(new Rectangle(10, 10, 600, 50));
    JButton button1 = new JButton("Just like it works in this code. Just Add ScrollPane to centerPanel That is in green backround");
    button1.setBounds(new Rectangle(10, 70, 600, 50));
    JButton button2 = new JButton("For clearity");
    button2.setBounds(new Rectangle(10, 130, 600, 50));
    centerPanel.add(button);
    centerPanel.add(button1);
    centerPanel.add(button2);
    centerPanel.setBackground(Color.GREEN);
    c.add(centerPanel, BorderLayout.CENTER);
}

private static void bottomPanel(Container c) {
    JPanel bottomPanel = new JPanel(); //Buttons that goes at the bottom of screen will go in here
    JPanel bottomInnerPanel = new JPanel();
    bottomInnerPanel.setLayout(new BorderLayout());
    bottomPanel.setLayout(new GridLayout());
    bottomInnerPanel.add(new JButton("Add"), BorderLayout.WEST);
    bottomInnerPanel.add(new JButton("Search"), BorderLayout.EAST);
    bottomPanel.add(bottomInnerPanel);
    bottomPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    c.add(bottomPanel, BorderLayout.SOUTH);
}

标签: javaswinglayoutnullscrollpane

解决方案


推荐阅读