[Java] 자바 swing의 레이아웃

Haeun Noh·2022년 9월 5일
0

JAVA

목록 보기
5/8
post-thumbnail

0905


전공심화 동아리에서 배운 Layout에 대해 정리해보자.
1학년 1학기 방과후에서 배웠던 html시간에서도 배워서 알고있는 반가운 이름이다.



레이아웃(Layout)

레이아웃은 현재 패널 크기에 따라 배치된 UI의 위치와 크기가 정해진 규칙에 따라서 변경된다.

레이아웃의 위, 아래의 구역이 먼저 할당이 된 후, 왼쪽, 오른쪽, 그리고 남은 부분은 센터 순서대로 구역이 할당된다.
이것은 컴퓨터가 정해준다.


Java swing에서 쓰이는 레이아웃의 종류는 다양하지만 2주차에서는 BorderLayout FlowLayout을 배웠다.


BorderLayout

: JFrame의 기본 레이아웃으로 컴포넌트들을 상,하,좌,우,중앙으로 배치한다.

레이아웃 소스코드를 실행한 결과창

this.setLayout(new BorderLayout());

BorderLayout을 사용한다고 말해주고,

this.add(new JButton("클릭!"));

BorderLayout의 중앙에 "클릭!"버튼을 추가하고,
(, BorderLayout.CENTER) 생략

this.add(new JButton("남쪽"), BorderLayout.SOUTH);

BorderLayout의 남쪽에 "남쪽"버튼을 추가하고,

this.add(new JButton("북!"), BorderLayout.NORTH);

BorderLayout의 북쪽에 "북!"버튼을 추가하고,

this.add(new JButton("동"), BorderLayout.EAST);

BorderLayout의 동쪽에 "동"버튼을 추가하고,

this.add(new JButton("서쪽"), BorderLayout.WEST);

BorderLayout의 서쪽에 "서"버튼을 추가하면 다음과 같은 화면이 나온다.


이번에는 FlowLayout에 대해서 배워보자.

FlowLayout

: 배치된 순서대로 쭉 나열함

FlowLayoutpanel

this.setLayout(new FlowLayout(FlowLayout.CENTER, 20,10));

Layout을 센터로 두고 레이아웃 사이간의 간격()을 20, 10만큼 가진다.

this.add(new JButton("클릭!"));

FlowLayout의 센터에 "클릭!" 버튼을 추가하고,

this.add(new JButton("남쪽"));

FlowLayout의 센터에 "남쪽" 버튼을 추가하고,

this.add(new JButton("북!"));

FlowLayout의 센터에 "북!" 버튼을 추가하고,

this.add(new JButton("동"));

FlowLayout의 센터에 "동" 버튼을 추가하고,

this.add(new JButton("서"));

FlowLayout의 센터에 "서" 버튼을 추가한다.

this.add(new JLabel("ID: "));

JLabel"ID: "를 추가하고,

this.add(new JTextField(20));

JTextField로 텍스트 20문자 분량을 입력할 수 있도록 설정하고,

this.add(new JButton("로그인"));

JButton으로 "로그인"버튼을 생성한다.

이렇게 입력하면 다음과 같은 창이 나온다.



profile
기록의 힘을 믿는 개발자, 노하은입니다!

0개의 댓글