import javax.swing.*;
import java.awt.*;
public class GridLayoutPosition extends JFrame {
public GridLayoutPosition() {
}
// 网格布局管理器示例
public GridLayoutPosition(int width, int height) {
this.setLayout(new GridLayout(7, 3, 5, 5));
for (int i = 0; i < 20; i++) {
add(new JButton("but" + i));
}
int[] screenSize = this.calcScreen(width, height);
this.setLocation(screenSize[0], screenSize[1]);
this.setSize(width, height);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
// 窗口屏幕居中
private int[] calcScreen(int width, int height) {
int[] screenSize = new int[2];
screenSize[0] = getToolkit().getScreenSize().width;
screenSize[1] = getToolkit().getScreenSize().height;
screenSize[0] = (screenSize[0] - width) / 2;
screenSize[1] = (screenSize[1] - height) / 2;
return screenSize;
}
public static void main(String[] args) {
new GridLayoutPosition(300, 300);
}
}