Dexter Moregan
Dexter Moregan

Reputation: 161

Components in GridLayout don't show properly

I create a GridLayout Frame with 2 rows and 3 column. I put 3 JLabel in the first row and each column. When I try to run, the third label is in the second row and the first column as show below

screenshot

Why does it happen?

Here the code

  JFrame windows = new JFrame("Shop");
  windows.setLayout(new GridLayout(2,3));
  JLabel prodlabel = new JLabel("Products");
  windows.add(prodlabel);
  JLabel spacelabel = new JLabel(" mid ");
  windows.add(spacelabel);
  JLabel shoplabel = new JLabel("Shopping List");
  windows.add(shoplabel);
  windows.setSize(1360, 728);
  windows.setVisible(true);

Upvotes: 0

Views: 1151

Answers (3)

PakkuDon
PakkuDon

Reputation: 1615

It has to do with the way GridLayout behaves when both the rows and columns are set to non-zero values. The LayoutManager decides on a column count itself based on the number of rows and the container's component count.

You can instead set the number of rows to 0 and set columns to 3. The LayoutManager will add more rows as you add more components to the container.

windows.setLayout(new GridLayout(0,3));

Edit: Wording, and here's a link to the Java Tutorial on GridLayout which may or may not have more information related to the matter.

Upvotes: 1

alex2410
alex2410

Reputation: 10994

That happens because you use GridLayout which resise component to whole cell(vertically/horizontally) and when you add component to that, it places them one by one firstly place components to row and them switching column, when row is full. You need to use another LayoutManager.

For example try to use GridBagLayout.

Or you can fix it by using one rownew GridLayout(1,3).

Upvotes: 0

pavan
pavan

Reputation: 34

You set layout for 6 elements. Try to add all 6 elements an run it

Upvotes: 0

Related Questions