Adding a button anywhere in a JPanel

Hairr picture Hairr · Nov 24, 2012 · Viewed 29.6k times · Source

Without using the Swing GUI on Eclipse, I've been struggling with adding a button to a JFrame anywhere in the frame (so no BorderLayout.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.

Answer

ErikFWinter picture ErikFWinter · Nov 24, 2012

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