최원종의 개발 블로그

좌표값으로 컴포넌트 배치 본문

Java/SWING

좌표값으로 컴포넌트 배치

chl6698 2026. 3. 9. 12:36

배치관리자 - 설정에 null 값을 주면 좌표 기준으로 컴포넌트들을 배치할 수 있다

 

※실행화면 버그 해결 참고※

private final void run() {
    initData();
    setInitLayout();
    //버그해결
    revalidate();
}

-코드

package com.tenco.swing.ch04;

import javax.swing.*;

//배치 관리자 - 설정에null값을 주면 좌표 기준으로 컴포넌트들을 배치할 수 있다
public class NoLayout1 extends JFrame {

    private JButton button1;
    private JButton button2;
    private JButton button3;


    public NoLayout1() {
        setTitle("좌표 기반으로 버튼 배치하기");
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void initData() {
        button1 = new JButton("button1");
        button2 = new JButton("button2");
        button3 = new JButton("button3");
    }

    private void setInitLayout() {
        //좌표값으로 배치
        setLayout(null);
        //주의점: 좌표 기반으로 배치 관리자 사용시
        //반드시 컴포넌트에 크기를 지정해야 하고 추가로 x, y를 지정해주어야한다

        button1.setSize(100, 100);
        button2.setSize(100, 100);
        button3.setSize(100, 100);
        button1.setLocation(200, 150);
        button2.setLocation(0, 0);
        button3.setLocation(385, 362);

        add(button1);
        add(button2);
        add(button3);
    }

    private final void run() {
        initData();
        setInitLayout();
        //버그해결
        revalidate();
    }

    //테스트 코드
    public static void main(String[] args) {
        NoLayout1 noLayout1 = new NoLayout1();//다른 곳에서 이 녀석을 부를 이름이 없다 -> 익명 클래스
        noLayout1.run();
    }
}

 

-실행화면

'Java > SWING' 카테고리의 다른 글

이벤트 리스너(ActionListener)  (0) 2026.03.16
패널 만들어 보기  (0) 2026.03.09
기본적인 컴포넌트  (0) 2026.03.09
BoarderLayout  (0) 2026.03.06
JFrame  (0) 2026.03.06