JLabel, 레이블 컴포넌트
JLabel
JLabel은 문자열이나 이미지를 스크린에 출력하는 레이블 컴포넌트를 만드는 클래스입니다.
레이블 컴포넌트 생성
레이블 컴포넌트 레이블이라고도 부르며, 다음 생성자를 이용하여 생성합니다.
JLabel() // 빈 레이블
JLabel(Icon image) // 이미지 레이블
JLabel(String text) // 문자열 레이블
JLabel(String text, Icon image, int hAlign) // 문자열과 이미지를 모두 가진 레이블
hAlign: 수평 정렬 값으로 SwitchConstant.LEFT, SwingConstant.RIGHT, SwingConstant.CENTER 중 하나
문자열 레이블 생성
JLabel textLabel = new JLabel("사랑합니다");
이미지 레이블 생성
이미지를 가진 레이블을 생성하기 위해서는, ImageIcon 클래스를 이용하여 이미지 파일로부터 이미지 객체를 생성하고, JLabel로 이미지 레이블을 생성합니다. 다음은 sunset.jpg 이미지를 읽어 이미지 레이블을 만드는 코드입니다.
ImageIcon image = new ImageIcon("images/subset.jpg");
JLabel imageLabel = new Label(image);
sunset.jpg 파일의 경로명은 "images/sunset.jpg"이므로 이클립스의 경우 sunset.jpg는 프로젝트의 images 폴더에 있어야 합니다.
문자열, 이미지, 수평 정렬 값을 가진 레이블 생성
다음 코드는 "사랑합니다"라는 문자열과 sunset.jpg 이미지를 함께 가진 레이블을 생성하고, 문자열과 이미지를 레이블 컴포넌트 영역 내에 중앙 정렬합니다.
ImageIcon image = new ImageIcon("images/sunset.jpg");
JLabel label = new JLabel("사랑합니다", image, SwingConstants.CENTER);
JLabel을 이용한 레이블 만들기
import javax.swing.*;
import java.awt.*;
public class LabelEx extends JFrame {
public LabelEx() {
setTitle("레이블 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
// 문자열 레이블 생성
JLabel textLabel = new JLabel("사랑합니다.");
// 이미지 레이블 생성
ImageIcon beauty = new ImageIcon("images/beauty.jpg"); // 이미지 로딩
JLabel imageLabel = new JLabel(beauty); // 이미지 레이블 생성
// 문자열과 이미지를 모두 가진 레이블 생성
ImageIcon normalIcon = new ImageIcon("images/normalIcon.gif"); // 이미지 로딩
JLabel label = new JLabel("보고싶으면 전화하세요",
normalIcon, SwingConstants.CENTER); // 레이블 생성
// 컨텐트팬에 3개의 레이블 부착
c.add(textLabel);
c.add(imageLabel);
c.add(label);
setSize(400, 600);
setVisible(true);
}
public static void main(String[] args) {
new LabelEx();
}
}
[실행 결과]

'프로그래밍 언어 > JAVA' 카테고리의 다른 글
| JCheckbox, 체크박스 컴포넌트 (2) | 2025.06.28 |
|---|---|
| JButton, 버튼 컴포넌트 (1) | 2025.06.25 |
| 스윙 컴포넌트 소개 (2) | 2025.06.20 |
| MouseEvent와 MouseListener, MouseMotionListener, MouseWheelListener (1) | 2025.06.17 |
| KeyEvent와 KeyListener (1) | 2025.06.14 |