// education

자바 GUI 스윙(Swing) 컴포넌트와 이벤트 처리

사용자가 마우스와 키보드로 그래픽 창과 상호작용하는 GUI(Graphical User Interface) 스윙(Swing) 프로그래밍과 이벤트 처리 모델을 익힙니다.


1. Swing GUI 용어 사전 (Glossary)


2. 윈도우 계산기 화면 GUI Swing 완성 예제

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleCalculatorGUI extends JFrame {
    private JTextField num1Field, num2Field;
    private JLabel resultLabel;

    public SimpleCalculatorGUI() {
        setTitle("DAVHAVE 자바 GUI 계산기");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout()); // 레이아웃 배치

        // 컴포넌트 생성 및 배치
        add(new JLabel("숫자 1:"));
        num1Field = new JTextField(5);
        add(num1Field);

        add(new JLabel("숫자 2:"));
        num2Field = new JTextField(5);
        add(num2Field);

        JButton addBtn = new JButton("더하기");
        add(addBtn);

        resultLabel = new JLabel("결과: ");
        add(resultLabel);

        // 버튼 이벤트 처리 (ActionListener)
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int n1 = Integer.parseInt(num1Field.getText());
                    int n2 = Integer.parseInt(num2Field.getText());
                    int sum = n1 + n2;
                    resultLabel.setText("결과: " + sum);
                } catch (NumberFormatException ex) {
                    resultLabel.setText("올바른 숫자를 입력하세요!");
                }
            }
        });

        setVisible(true); // 윈도우 창 표시
    }

    public static void main(String[] args) {
        new SimpleCalculatorGUI();
    }
}

3. 자주 묻는 질문 (Q&A)

Q. Swing 구동 시 UI 스레드 안전성을 유지하려면? A. Swing 컴포넌트 생성 및 갱신은 반드시 SwingUtilities.invokeLater(() -> { ... }); 메소드를 사용하여 EDT(Event Dispatch Thread) 상에서 실행시켜야 안전합니다.

← 이전자바 멀티스레딩(Multithreading)과 동시성 제어 다음 →자바 소켓(Socket) 네트워크 프로그래밍