tags:

views:

42

answers:

3
+1  Q: 

About GridLayout.

Hi, if I have code like so:

class X extends JFrame
{
X()
{
setLayout(new GridLayout(3,3));
JButton b = new JButton("A-ha");
/*I would like to add this button in the center of this grid (2,2)*/
//How can I do it?
}
};

Thanks.

+1  A: 

As what I know, you have to fill all the previous cells before. So you need to add 4 components before you can add the center component. Hmm, it could be a better layoutmanager.

What are you trying to do? Maybe BorderLayout is what you are looking for?

Jonas
God Almighty I'll be slagged by saying this but why is it that in java everything is so.... Why couldn't they provide a way in which I would be able to write add(button,(2,2)); Why? For God's sake, why? Another simplification for the famous "most common case"?
There is nothing we can do
Well, I don't know about the rest of the other developers, but I do not think that Java's strong point is in its GUI.
npinti
@Knowing me knowing you: I agree.
Jonas
@npinti: Java Swing can be a good choice if you want a cross platform GUI.
Jonas
Yes I know. But it seems that Java can give you quite a headache if you would like to do something that is a bit out of the box.
npinti
+1  A: 

You might want to take a look at the GridBag Layout

npinti
Does GridBagLayout let's me do this?
There is nothing we can do
According to that tutorial,"You can set the following GridBagConstraints instance variables:gridx, gridySpecify the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0. Use GridBagConstraints.RELATIVE (the default value) to specify that the component be placed just to the right of (for gridx) or just below (for gridy) the component that was added to the container just before this component was added. "Follow the links for more details :)
npinti
+1  A: 

This centres vertically and horizontally

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class centerbutton extends JFrame{
   public centerbutton(){
      setLayout(new BorderLayout());

      JPanel panel = new JPanel();
      JButton button = new JButton("A-ha!");
      button.setAlignmentX(
      Component.CENTER_ALIGNMENT);
      panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
      panel.add(Box.createVerticalGlue());
      panel.add(button);
      panel.add(Box.createVerticalGlue());

      getContentPane().add(panel);

      setVisible(true);
   }

   public static void main(String[] args) {
      new centerbutton();
   }

}
colinjameswebb
I basically stole it from http://answers.yahoo.com/question/index?qid=20090729150118AAHGvrI
colinjameswebb