Adding a button anywhere in a JPanel
You can use different Panels with different LayoutMangers to arrange the GUI as you like.
Have a look here for some common LayoutManagers: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
Otherwise you could use the null Layout (panel.setLayout(null)) and place all components by setting the position. But I would recommend you the LayoutMangers
Related videos on Youtube
Hairr
Updated on July 09, 2020Comments
-
Hairr almost 4 years
Without using the Swing GUI on Eclipse, I've been struggling with adding a button to a
JFrame
anywhere in the frame (so noBorderLayout.CENTER
). I can't get past:JPanel panel = new JPanel(); JButton OKButton = new JButton("OK"); OKButton.addActionListener(new MyAction()); panel.add(OKButton,BorderLayout.CENTER);
So would something like this be completely redesigned or is there something I'm missing?
EDIT: By Anywhere (as I'm planning to add more than one button/label to a frame), I meant perhaps a coordinate on the frame. So other than dead center, (example) 75% from the left and 25% down.
-
Hovercraft Full Of Eels over 11 yearsYour best bet is to read up on and use the layout managers as they will make your GUI creation much easier. You can find the tutorial here.
-
Andrew Thompson over 11 years"75% from the left and 25% down"
GridBagLayout
accepts weights. I think so doesMigLayout
& possibly other 3rd party layouts.
-