I have a JPanel with a vertical BoxLayout on top of a JPanel with a null layout.
I would like the JPanel with the BoxLayout to grow as the components are being added
Off the bat, what I would change:
public static void main (String[] args) {
JFrame f = new JFrame();
//f.setSize(500,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel total = new JPanel();
//total.setLayout(null); //<-- this is usually a bad idea, but you can keep it
// if you want to specify an EXACT location
// for your JPanel
total.setPreferredSize(500, 500);
total.setBackground(Color.green);
JPanel box = new JPanel();
//box.setLocation(100,200);
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
box.add(new JButton("test"));
box.add(new JLabel("hey"));
total.add(box);
f.add(total);
f.pack();
f.setVisible(true);
}
Once you have that basis, all you need to do to dynamically change the size of a JPanel is:
panel.setSize(width, heightOfComponentWithin * numberOfComponents);
container.repaint(); //<-- Im not sure if you also have to call panel.repaint(),
// you probably don't have to.
I would also recommend using a scroll view, just in case the JPanel starts getting out of view. Good Luck!