AHil Rajwani
AHil Rajwani

Reputation: 21

How do you set the position of button in grid layout?

My code:

public class Form {
    public static void main(String[] args) {
        Form form = new Form();
        form.go();
    }

    public void go() {
        JFrame form = new JFrame();
        GridLayout layout = new GridLayout(2,7);
        Label nameLabel = new Label("Name");
        form.setLayout(layout);
        JTextField nameBox = new JTextField();
        form.getContentPane().add(nameLabel);
        form.getContentPane().add(nameBox);
        form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        form.setSize(500,500);
        form.setVisible(true);
    }
}

Now, how can I set this position of the JTextField so its 2,7 and not 1,2?

Upvotes: 2

Views: 34770

Answers (3)

Eng.Fouad
Eng.Fouad

Reputation: 117597

Try adding empty components into the positions before 2,7 , something like:

form.add(nameLabel);
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(new JPanel());
form.add(nameBox);

Upvotes: 4

buch11
buch11

Reputation: 882

seems that you better use GridBag layout,and use gridx gridy constraints to position your components...Here is a tutorial from java: http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html As far as I know you cannot directly put components wherever you want using grid layout( @Paŭlo Ebermann has mentioned the same thing)

Upvotes: 3

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74760

A GridLayout will always sort the components of the container in the order they are in the container. You can't put a component at a specific place, other than by inserting dummy components for all the places before.

You might want to try other layout managers. GridBagLayout can do this, but is quite more complicated to use.

Upvotes: 2

Related Questions