최원종의 개발 블로그

패널 만들어 보기 본문

Java/SWING

패널 만들어 보기

chl6698 2026. 3. 9. 12:36

실습 코드

package com.tenco.swing.ch05;

import javax.swing.*;
import java.awt.*;

public class MyPanel extends JFrame {
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;

    // 패널 - 컴포넌트들을 그룹화 시킬 수 있다( 즉 각 패널마다 레이아웃 다르게 설정 가능)
    private JPanel panel1;
    private JPanel panel2;

    public MyPanel() {
        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");
        button4 = new JButton("button4");

        panel1 = new JPanel();
        panel2 = new JPanel();
    }

    //R G B ->삼원색
    //0 0 0 -> 흰색
    // 255 255 255 -> 검은색

    private void setInitLayout() {
        //루트 패널에 배치 관리자 --> Grid
        setLayout(new GridLayout(2, 1));
        panel1.setBackground(Color.BLACK);
        panel2.setBackground(Color.BLUE);
        //JFrame
        super.add(panel1);
        add(panel2);

        //패널 1에 배치 관리자는 수평 수직으로 배치하는 녀석
        panel1.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
        panel1.add(button1);
        panel1.add(button2);
        button1.setLocation(0, 0);
        button2.setLocation(0, 0);

        //패널 2에 관리자 역시 수평 수직
        panel2.setLayout(new FlowLayout(FlowLayout.RIGHT, 20, 20));
        panel2.add(button3);
        panel2.add(button4);
        button3.setLocation(0, 300);
        button4.setLocation(400, 270);


    }

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

    //테스트 코드
    public static void main(String[] args) {
        MyPanel myPanel = new MyPanel();
        myPanel.run();
    }
}


실행화면

패널 화면

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

Key Listener  (0) 2026.03.17
이벤트 리스너(ActionListener)  (0) 2026.03.16
좌표값으로 컴포넌트 배치  (0) 2026.03.09
기본적인 컴포넌트  (0) 2026.03.09
BoarderLayout  (0) 2026.03.06