How do you layout these components centered
Here is my program, its like a 3 number hi-low game.
http://i49.tinypic.com/2qn1w5e.jpg
I am using for the top, middle, and bottom rows. Then inside those panels I use gridlayout to layout the objects. I want to know if instead of them being in their respective grids on the left hand side, if they could be centered inside of their grid?
I tried using setAlignmentX and that didn't work. I don't really know how to go about it. I'll post a snippet of my code that is important.
Code :
//middle panel setup
JPanel middle = new JPanel();
middle.setLayout(new GridLayout(1, 3));
higher = new JButton("Higher");
higher.setAlignmentX(CENTER_ALIGNMENT);
middle.add(higher);
or = new JLabel("OR");
or.setAlignmentX(CENTER_ALIGNMENT);
middle.add(or);
lower = new JButton("Lower");
lower.setAlignmentX(CENTER_ALIGNMENT);
middle.add(lower);
pane.add(middle);
EDIT: I drew what I want it to be like in paint... :D
http://i48.tinypic.com/143fj41.jpg
Re: How do you layout these components centered
You could combine it with BoxLayout and utilize horizontal and vertical glues for the alignment. In your case, you could use this layout inside the GridLayout, perhaps create a new type of JPanel
Code :
public class HorizontallyCenteredJPanel extends JPanel{
public HorizontallyCenteredJPanel(Component c){
super();
add(Box.createHorizontalGlue());
add(c);
add(Box.createHorizontalGlue());
}
}
Or something like this....then just add your components to this, and in turn add it to your GridLayout JPanel.
Re: How do you layout these components centered
Another way is to add each component to a JPanel with a GridBagLayout WITHOUT using a GridBagConstraints, which will center the component in the JPanel at its preferredSize, and then add these JPanels to your original GridLayout.
db
edit But a more suitable approach might be to just use a GridBagLayout with a GridBagConstraints set to fill=NONE and anchor=CENTER. Of course, if the individual components don't have the same preferred size, this could lead to an uneven grid spacing.