我需要在添加新组件时动态调整 JPanel 的大小

Iva*_*nin 1 java user-interface jpanel jscrollpane

我需要让用户向我的 JFrame 添加更多文本字段,因此一旦框架的大小超过其原始值,滚动窗格就会介入。由于我无法将 JScrollPane 添加到 JFrame 以启用滚动,因此我决定将 JPanel 放在JFrame 并将 JPanel 对象传递给 JScrollPane 构造函数。滚动现在可以正常工作,但只能直到它到达 JPanel 的边界。问题是 JPanel 的大小保持原样,不会动态拉伸。发生的情况是我的代码中的按钮用完了 300x300 大小的 JPanel 的所有空间,但我想要做的是在这些控件用完其原始空间后让 JPanel 拉伸。请指教。

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;


public class Skrol {
    public static void main(String[] args) {


        JFrame f = new JFrame();
        f.setLayout(new FlowLayout());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel();


        p.setPreferredSize(new Dimension(400,400));



        JScrollPane jsp = new JScrollPane(p);

        jsp.setPreferredSize(new Dimension(300,300));
        jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

            for(int i=0;i<100;i++)
                {
                    JButton b = new JButton("Button "+i);
                    p.add(b);
                }
        f.add(jsp);
        f.setSize(new Dimension(600,600));
        f.setLocation(300, 300);
        f.setVisible(true);

    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我将您的 Layout 更改JPanelGridLayout,因此它的大小仅由 Layoutmanager 根据面板上的组件处理。

    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p = new JPanel(new GridLayout(0, 5));
    JScrollPane jsp = new JScrollPane(p);

    jsp.setPreferredSize(new Dimension(300,300));
    jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    for (int i = 0; i < 100; i++) {
        JButton b = new JButton("Button " + i);
        p.add(b);
    }

    f.add(jsp, BorderLayout.CENTER);
    f.setLocation(300, 300);
    f.setVisible(true);
    f.pack();
Run Code Online (Sandbox Code Playgroud)