user10663920
user10663920

Reputation:

How do I use GridLayout in Swing?

I tried making a GUI with Swing. But when I trief using GridLayout every element sudenly disappears and I don't know why. Can someone explain and/or provide a solution?

I've tried looking at the Tutorial for it, but it didn't help very much. and I experimented a bit around but still not working. :(

JPanel pan1 = new JPanel();
JPanel pan2 = new JPanel();
JPanel pan3 = new JPanel();
JPanel pan4 = new JPanel();
JPanel pan5 = new JPanel();
add(pan1);
add(pan2);
add(pan3);
add(pan4);
add(pan5);
pan1.setLayout(new GridLayout(0, 1));
pan2.setLayout(new GridLayout(1, 1));
pan3.setLayout(new GridLayout(2, 1));
pan4.setLayout(new GridLayout(3, 1));
pan5.setLayout(new GridLayout(4, 1));

I expected having 1 Element in every 0-4 columns but it shows me a blank screen.

Upvotes: 0

Views: 133

Answers (1)

Wulf
Wulf

Reputation: 712

I expected having 1 Element in every 0-4 columns but it shows me a blank screen.

No. You have 5 Panels and each of them has a gridlayout.

pan1.setLayout(new GridLayout(0, 1)); //pan1 gets a new GridLayout
pan2.setLayout(new GridLayout(1, 1)); //pan2 gets a new GridLayout
pan3.setLayout(new GridLayout(2, 1)); //...
pan4.setLayout(new GridLayout(3, 1));
pan5.setLayout(new GridLayout(4, 1));

You need:

setLayout(new GirdLayout(1,5);  //1 Row 5 Columns
add(pan1);
add(pan2);
add(pan3);
add(pan4);
add(pan5);

Upvotes: 3

Related Questions