I don't think the API has a setWidth or similar function for JButtons. The width of the buttons is determined by the text inside the button. So the "ABC" will be shorter than "ABCDEF". If you are keen on fixing the width you probably need to do a bit of string manipulation setting each text for the JButtons the same before initializing the JButtons.
GridLayout sounds like a good idea. If you can't make that work you could start with this class. It overrides the getPreferredSize method by referring to another button's preferred size. You might want to modify it by adding constructors or allowing it to look at more other buttons.
Sorry if I am bringing an old thread back to life inappropriately, but I am currently have the same problem.
I have a swing application using GridBagLayout. It doesn't look pretty, but it gets the job done. However, I can't get anything centered or looking right no matter what I do.
Here is the code for the item adding and GridBag constraints:
I know I could just do constraints beforehand and add as normal, but it seems to get the job done anyway so I left it. However, this is clearly not doing the trick... now, if I change it around, it still does nothing. Here is a picture of my program:
If there is any more information needed, I'd be happy to provide... I've been at this for hours now trying to make it all look right and I just can't. Any tips? Can't I just say, "Hey, I want the column to be this big, NO BIGGER, and button, I want you to fill up that column, even if the text overlaps." Isn't there ANY WAY to work this around so I can get a static look for my program rather than having to see what it does at runtime? I heard I shouldn't use setPreferredSize(), so I don't plan to, but it seems like my columns are just picking whatever sizes they should and I don't get how to effectively position everything to make it look... well, good.
Try to create Box by Box.createHorizontalBox() and add your buttons to it, then try to align that Box the way you want
Joined: Oct 02, 2009
A question about the boxes... if I create a box, should I put it in the bottom-left square of the GridBagLayout and give it the width of all the columns so it can stretch, or what?
Joined: Oct 02, 2009
Sorry to double-post... not sure if there are rules on that, but on the forum I moderate (on another website, obviously), we usually have a ten-minute rule for double-posting and editing, so I hope something like that applies here in terms of spam, if at all...
Anyway, the box worked GREAT! How can I space my buttons out within the box, though? Like can I give them a bit of padding somehow?