본문 바로가기

언어/Java

[ Java ] swing 라이브러리 간단하게 사용해 보기

반응형

Swing은 Java의 표준 GUI 툴킷으로, 다양한 GUI 컴포넌트를 사용하여 데스크탑 애플리케이션을 만들 수 있습니다. 여기에는 버튼, 텍스트 필드, 레이블, 체크박스, 라디오 버튼, 패널, 프레임 등의 컴포넌트가 포함됩니다. Swing은 Java Foundation Classes(JFC)의 일부로, 플랫폼 독립적인 GUI 애플리케이션을 개발하는 데 사용됩니다.

아래에 간단한 Java Swing 애플리케이션 예제를 만들어보겠습니다. 이 예제에서는 기본적인 JFrame을 생성하고, 버튼을 추가하고, 버튼 클릭 시 메시지 다이얼로그를 표시하는 간단한 애플리케이션을 구현합니다.

Java Swing 애플리케이션 예제

1. 프로젝트 구조

MySwingApp/
└── src/
    └── com/
        └── example/
            └── MySwingApp.java

2. MySwingApp.java

package com.example;

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

public class MySwingApp {
    public static void main(String[] args) {
        // Create a new JFrame instance
        JFrame frame = new JFrame("My Swing Application");

        // Set the default close operation
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a new JButton instance
        JButton button = new JButton("Click Me!");

        // Add an ActionListener to the button
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Show a message dialog when the button is clicked
                JOptionPane.showMessageDialog(frame, "Button was clicked!");
            }
        });

        // Add the button to the frame
        frame.getContentPane().add(button);

        // Set the size of the frame
        frame.setSize(300, 200);

        // Center the frame on the screen
        frame.setLocationRelativeTo(null);

        // Make the frame visible
        frame.setVisible(true);
    }
}

설명

  1. JFrame 생성: JFrame 객체를 생성하고 기본 닫기 동작을 설정합니다.
  2. JButton 생성: "Click Me!" 라는 텍스트가 있는 JButton 객체를 생성합니다.
  3. ActionListener 추가: 버튼에 ActionListener를 추가하여 버튼이 클릭될 때 메시지 다이얼로그를 표시하도록 합니다.
  4. 버튼을 프레임에 추가: frame.getContentPane().add(button)을 사용하여 버튼을 프레임에 추가합니다.
  5. 프레임 크기 설정: frame.setSize(300, 200)을 사용하여 프레임의 크기를 설정합니다.
  6. 프레임을 화면 중앙에 배치: frame.setLocationRelativeTo(null)을 사용하여 프레임을 화면 중앙에 배치합니다.
  7. 프레임을 표시: frame.setVisible(true)을 사용하여 프레임을 화면에 표시합니다.

이 예제는 간단하지만, Java Swing을 사용하여 GUI 애플리케이션을 만드는 방법을 이해하는 데 도움이 됩니다. Swing을 사용하면 이와 같은 기본 컴포넌트 외에도 다양한 고급 컴포넌트를 활용하여 복잡한 GUI를 만들 수 있습니다.

반응형