1

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

    }
}
4

2 回答 2

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();
于 2013-08-28T15:30:10.277 回答
-2

选择布局下的 Miglayout 选项。我发现这是最简单的方法

https://i.stack.imgur.com/XKHVu.png

于 2019-09-19T18:16:45.997 回答