I've a few questions:
First, and most importantly, why can you run a GUI program with a frame, a couple panels, buttons, etc. several times - without changing anything - and half the time components are displayed in the frame, and the other half of the time nothing is displayed... literally, I change nothing in the code and it's the most frustrating problem to have. Sometimes stuff appears, sometimes nothing. I'm using Eclipse and just have the below code in a main method.
Secondly, can someone please explain clearly how Frames, Panels, and Layouts work?
JFrame f = new JFrame();
f.setSize(400, 400);
f.setLayout(new BorderLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
JPanel p = new JPanel();
JButton alpha = new JButton();
JButton bravo = new JButton();
alpha.setLabel("Alpha");
bravo.setLabel("Bravo");
p.add(alpha, BorderLayout.WEST);
p.add(bravo, BorderLayout.EAST);
p.add(new JLabel("Charlie"), BorderLayout.SOUTH);
f.add(p);
The above sometimes works, and when it does it's not laying out how I understand from Oracle pages and tutorials. I create a frame (with no default layout), create a panel with two buttons that should be next to each other (WEST, EAST), then add a label to the bottom of the panel - and that whole panel is added to the frame. However they are all added next to each other at the top of the frame, centered.
Can you only have one component per panel? Can you add multiple panels to a frame, and if so do they overlap?
FYI I have watched YouTube videos and read a few other posts here, nothing seems to explain the basics simply and thoroughly, so I thought a forum post would get better explanations.
Thanks