13

I need to put a button in the bottom right of an otherwise empty JPanel

 +-----------------------------------+
 |                                   |
 |                                   |
 |                                   |
 |                                   |
 |                                   |
 |                                   |
 |                                   |
 |                                   |
 |                      +-----------+|
 |                      | Click Me! ||
 |                      +-----------+|
 +-----------------------------------+

How do I do that? It should be easy right? I would like to find the correct layout manager rather than using a sequence of nested panels.

JPanel panel = new JPanel();
panel.setLayout(new SomeKindOfLayoutManagerThatDoesThis());
panel.add(new JButton("Click Me!"), SETTINGS);
Jan Hrcek
  • 626
  • 11
  • 24
Lucas
  • 1,869
  • 4
  • 20
  • 36
  • 1
    Could be useful - [How to put component in bottom-right corner with GridBagLayout](http://stackoverflow.com/q/7905731/1048330) – tenorsax Jun 23 '12 at 00:48
  • Is it the only component in the container? For a non-resizable container it could be achieved using an `EmptyBorder` on the button. – Andrew Thompson Jun 23 '12 at 06:06

2 Answers2

27

I would suggest using the Border Layout manager with Flow Layout.

something like:

this.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
JButton clickmeButton = new JButton("Click Me");
buttonPanel.add(clickmeButton);
this.add(buttonPanel,BorderLayout.SOUTH);
reesjones
  • 704
  • 3
  • 9
  • 28
henry bemis
  • 490
  • 3
  • 8
  • 1
    I used this in the end, with a little modification :) – Lucas Jun 23 '12 at 01:14
  • +1, Please see this [example](http://stackoverflow.com/questions/10741506/jbutton-positioning-issues/10742228#10742228) too :-) – nIcE cOw Jun 23 '12 at 01:59
  • 1
    Why was it so hard to find this answer? I've been googling and SO-ing for 1/2 hour, this is all I wanted. – Mike G Dec 16 '12 at 18:46
  • @mikeTheLiar: sorry to hear that. glad you ultimately found what you were looking for though. there's no guarantee, but for java-specific issues, there are a lot of knowledgeable people at http://www.coderanch.com/forums. it's another place you might also try. – henry bemis Feb 08 '13 at 18:56
4

You can use a combination of BoxLayout and size/alignment hints to achieve this.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141