Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Any better way?  RSS feed

 
Zee Ho
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, ranchers, I decide to place a button in to the centre of the frame, here is what I did.

I use a gridlayout as 3 x 3, place the button into the 5th position and set a empty JLabel to the others position. everything works perfectly.

I tried many ways, but it is the only one I can make the JButton display in a proper position and appropriate size, seems stupid. are there any better way to do it? thx in advance
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use BorderLayout on the frame and add your button to a JPanel first, then add the JPanel to the frame. This might not go to the exact centre of the frame, depending on its size.
 
Zee Ho
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I followed you way, is it right? but the button is in top-centre position rather than centre. I try to add a empty panel in the north postion, seems no use. Maybe I miss something.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this will work for the stated problem, but gridbaglayout is not easy to use

 
Zee Ho
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
woo. hoo.. excellent, thx very much.
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem with my solution is that the JPanel will be centred in the frame, but the button will be at the top left-most position in the panel. However, if the frame is relatively small (or has components at N, E, S, and W), the panel may resize to be a similar size to the button.

Welcome to the wonderful world of Swing layouts
 
Zee Ho
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
before do the swing coding, I thought css is the gel thing, seems I am wrong
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!