简体   繁体   中英

JFrame - Setting the Row and Column in a GridLayout

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class GridLayoutTest {

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("GridLayout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new GridLayout(3, 2));
    frame.add(new JButton("Button 1"));
    frame.add(new JButton("Button 2"));
    frame.add(new JButton("Button 3"));
    frame.add(new JButton("Button 4"));
    frame.add(new JButton("Button 5"));
    frame.add(new JButton("Button 6"));
    frame.add(new JButton("Button 7"));
    frame.add(new JButton("Button 8"));
    frame.pack();
    frame.setVisible(true);
  }
}

I got the code from this tutorial website: http://www.java2s.com/Tutorial/Java/0240__Swing/HowtoUseGridLayout.htm

This program displays 8 buttons on the screen. I'm having trouble understanding the layout arrangements of the buttons. Notice that row=3, and column=2. When I run the program, the arrangement of the button is row=3 and column=3....

Changing the number of rows actually changes the layout according to the given row number, but changing the number of columns doesn't changes the layout and the number of column will always remain as 2. Why is that? It might be a screen size issue.

It's the documented behavior of the GridLayout class. Did you read the docs?

When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number of rows and the total number of components in the layout. So, for example, if three rows and two columns have been specified and nine components are added to the layout, they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero.

"Specifying the number of columns affects the layout only when the number of rows is set to zero." Therefore, if you want to hold the number of columns constant, specify 0 for the rows:

    frame.setLayout(new GridLayout(0, 2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM