Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

HeadFirst BeatBox: Getting the buttons to be aligned center  RSS feed

 
Ken Shinbashi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am using the excellent book "Head First Java".

At the end of chapter 13, there is the code kitchen for BeatBox.

In regards to the buttons, I want to make them aligned center. The default is aligned left.

Here is what I think is the relevent code:



I think that this should work, but it is not working; the buttons still appear aligned left.

Can anyone asist me with this?

Thanks.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
setAlignmentX() does not place the component at left, center or right,
it creates the alignment point
eg if you have a button (L) set to left, and a button (C) set to center, L
will be in the center and C on the left, because the left edge of L will be
aligned to the center of C.

if all your buttons are aligned left, and you want them in the center, put the panel into a holding panel (default flowlayout), and add your boxlayout panel
to the holding panel
 
Ken Shinbashi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, thanks for the clarification.

So, would it be like:

JPanel holdPanel = new JPanel();
Box buttonBox = new Box(Y_AXIS);
holdPanel.add(buttonBox);

It seems that this would have the same problem as before, because the Box would be the single component in the JPanel, and the buttons inside the box will still have the same left alignment.

So, what would be the correct way of doing this? And, is there anyway to get a Box to center its components?

Thanks.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not really sure what you're trying to center

here's an example of centering the components in the box
(all components need to be set to CENTER, or 0.5f)



if it's the centering of the box itself, comment out the indicated line
and uncomment the other 4 lines, to see the difference
 
Ken Shinbashi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Michael.

I had made a mistake in my understanding.

I called setAlignmentX on the Box, when I should have been calling it on each button.

I thought that the Box had a property of AlignmentX that would automatically align its components at the place I specified. Instead, the property of alignment goes to each member component.


Thank you for showing me your example
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!