GridBagConstraints 클래스

GridBagConstraints 클래스

GridBagConstraints 클래스는 GridBagLayout 클래스를 사용해 배치되는 컴포넌트에 대한 제약 조건을 지정해요.

출처: Java API Reference

본문

GridBagLayout은 가장 유연한 AWT 레이아웃 중 하나예요. 각 컴포넌트는 GridBagConstraints로 배치 방식(셀 위치, 늘어남 정도, 정렬, 여백 등)을 정해요.

public class GridBagConstraints
extends Object
implements Cloneable, Serializable

주요 필드

  • gridx / gridy — 컴포넌트를 배치할 그리드 셀의 열·행 인덱스예요. RELATIVE를 쓰면 이전 컴포넌트의 상대 위치에 배치돼요.
  • gridwidth / gridheight — 컴포넌트가 차지하는 열·행 수예요. REMAINDER는 줄 끝까지, RELATIVE는 끝에서 두 번째 위치까지 차지해요.
  • weightx / weighty — 여분 공간을 컴포넌트에 할당할 가중치예요. 0보다 크면 컨테이너가 커질 때 늘어나요.
  • anchor — 여분 공간에서 컴포넌트 정렬 위치예요. CENTER, NORTH, SOUTH, EAST, WEST, NORTHWEST 등이 있어요.
  • fill — 컴포넌트를 셀 안에서 어떻게 채울지예요. NONE, HORIZONTAL, VERTICAL, BOTH가 있어요.
  • insets — 컴포넌트 바깥 여백(Insets)을 설정해요.
  • ipadx / ipady — 컴포넌트의 내부 패딩을 설정해요.

상수

  • static final int RELATIVE — 상대 위치 지정
  • static final int REMAINDER — 남은 줄 전체 차지
  • static final int NONE / HORIZONTAL / VERTICAL / BOTH — fill 값
  • static final int CENTER / NORTH / SOUTH / EAST / WEST 등 — anchor 값

생성자

  • GridBagConstraints() — 기본 제약 조건을 만들어요.
  • GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady) — 모든 값을 지정해 만들어요.

사용 예

GridBagConstraints c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0;
c.weightx = 1.0; c.fill = GridBagConstraints.HORIZONTAL;
panel.add(button1, c);
c.gridy = 1;
panel.add(button2, c);

GridBagConstraints 인스턴스는 재사용할 수 있으므로, 값만 바꿔가며 여러 컴포넌트에 적용해요.

더 알아보기