Hairr
Hairr

Reputation: 1108

Adding a button anywhere in a JPanel

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.

Upvotes: 7

Views: 32687

Answers (1)

Erik-RW
Erik-RW

Reputation: 173

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

Upvotes: 4

Related Questions