views:

395

answers:

6

Is there a way to add elements to a gridlayout that adds them horizontally instead of vertically? Basically i want to fill up an entire row with elements before it begins with the next.

Hope i made my question clear.

+4  A: 

That is how GridLayout works.

Jonathan Feinberg
A: 

The GridLayout, as the name suggests lays out components according to the number of columns and rows you specified in the constructor, and will move to the next row as soon as you have added the specified number of components.

From your question, it seems that a FlowLayout is more along the lines of what you're looking for.

Edit: I'm not sure why, but if you specify the number of rows as 0 (e.g. new GridLayout(0, 9), it seems to work properly.

Jared Russell
well, i tried adding 5 texfields to a 9x9 gridlayout, and the are on top of each other, not side by side. So it fills up a coloumn first, and then the moves on to the next coloumn, what I i want is filling up rows first :D
ev00l
A: 

I would suggest GridBagLayout and GridBagConstraints

It's a lot like a GridLayout, but with GridBagConstraints you can specify the x and y coordinates of the component, and you can do column and row spans.

It would look something like this:

GridBagLayout layout = new GridBagLayout();
GirdBagContraints c = new GridBagContraints();

JPanel panel = new JPanel();
JLabel label = new JLabel("foo");

panel.setLayout(layout);

c.gridx = 0;
c.gridy = 0;
panel.add(label, c);
jonescb
This looks like something really usefull. Is the x and y the location of the cell in the "table"?
ev00l
Yep, it's the cell's coordinates. Not the pixel coordinates of the container.
jonescb
Works like a charm. I have a for loop where i set the x and y before adding each element. Thank you very much!
ev00l
A: 

It is probberly me not understanding something :D This is the test code i used:

    this.setLayout(new FlowLayout());
    JPanel panel = new JPanel(new GridLayout(9, 9));
    panel.add(new JTextField("test"));
    panel.add(new JTextField("test"));
    panel.add(new JTextField("test"));
    panel.add(new JTextField("test"));
    panel.add(new JTextField("test"));
    add(panel);

This is in a jFrame. This gives me 5 textboxes on top of each other, instead of side by side.

ev00l
It is "probberly" you ignoring all of the answers you've been given, which lead you to the documentation and give you code that works. What else could you need?
Jonathan Feinberg
Sorry about that. I just couldn't find the answer in the documentation of gridlayout. Good for me that some guys here showed me some better layouts.
ev00l
A: 

I assume you meant to say that you want to fill up all the rows in a column before moving to the next column. If so, then use a custom layout manager

VerticalGridLayout

camickr
A: 

Actually you should use GroupLayout It's new (since jdk 1.6) and pretty awesome. It gives you a ton of flexibility in layout.

Chad Okere
Thank you for the tip :D
ev00l