I need to make my JPanel resize dynamically as new

2019-02-20 11:17发布

问题:

I need to let users add more text fields to my JFrame so once the size of the frame has exceeded its original value a scroll pane would step in. Since I cannot add JScrollPane to JFrame in order to enable scrolling I decided to put the JPanel on the JFrame and pass the JPanel object into the JScrollPane constructor. Scrolling now works fine but only until it has reached the borders of the JPanel. The thing is the size of JPanel stays as is and is not stretching dynamically. What happens is the buttons in my code are using up all the space of the JPanel being the size of 300x300 but what I want to do is have JPanel stretch once these controls have used up its original space. Please advise.

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);

    }
}

回答1:

I changed the Layout in your JPanel to GridLayout, so the Size of it is just handeld by the Layoutmanager depending on the components on the panel.

    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();