JOptionPane은 JComponent 클래스의 하위 클래스로, 모달(modal) 대화 상자를 생성하고 커스터마이징할 수 있는 다양한 정적(static) 메서드를 제공합니다. JDialog 클래스를 직접 사용하는 것보다 JOptionPane 클래스를 활용하면 코드의 복잡도를 크게 줄일 수 있습니다.
JOptionPane은 기본적으로 네 가지 표준 아이콘(질문(question), 정보(information), 경고(warning), 오류(error)) 중 하나를 사용해 대화 상자를 표시하며, 필요에 따라 사용자가 직접 지정한 커스텀 아이콘을 적용할 수도 있습니다.
기본 상태의 JOptionPane 메시지 대화 상자는 한 줄 텍스트만 지원합니다. 하지만 JTextArea 클래스를 커스터마이징하여 대화 상자에 삽입하면, 스크롤이 가능한 긴 텍스트도 손쉽게 구현할 수 있습니다. 아래 예제는 JTextArea에 긴 메시지를 설정하고 JScrollPane으로 감싸서 JOptionPane에 표시하는 방법을 보여줍니다.
예제 코드
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JOptionPaneScrollTextMessage extends JFrame {
private JButton btn;
String msg;
public JOptionPaneScrollTextMessage() {
setTitle("JOptionPaneScrollTextMessage Test");
msg = " Java is a programming language that produces software for multiple platforms.\n When a programmer writes a Java application, the compiled code\n" + "(known as bytecode) runs on most operating systems (OS), including \n Windows, Linux and Mac OS. Java derives much of its syntax \n from the C and C++" + "programming languages.\n Java was developed in the mid-1990s by James A. Gosling, a former computer scientist with Sun Microsystems.";
btn = new JButton("Show Dialog");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JTextArea jta = new JTextArea(5, 15);
jta.setText(msg);
jta.setEditable(false);
JScrollPane jsp = new JScrollPane(jta);
JOptionPane.showMessageDialog(null, jsp);
}
});
add(btn, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JOptionPaneScrollTextMessage();
}
}코드 설명
- JTextArea(5, 15): 5행 15열 크기의 텍스트 영역을 생성하여 긴 메시지를 담을 공간을 만듭니다.
- jta.setEditable(false): 텍스트 영역을 읽기 전용으로 설정해 사용자가 내용을 수정하지 못하도록 합니다.
- JScrollPane: JTextArea를 스크롤 패널로 감싸서, 텍스트가 영역을 초과할 경우 스크롤바가 자동으로 나타나도록 합니다.
- JOptionPane.showMessageDialog(): 컴포넌트를 전달받아 해당 내용을 포함한 모달 메시지 대화 상자를 화면에 표시합니다.
실행 결과
프로그램을 실행하고 Show Dialog 버튼을 클릭하면, 스크롤 가능한 텍스트 영역과 함께 긴 메시지가 담긴 JOptionPane 대화 상자가 나타납니다.
