본문 바로가기

Swing/JTextEditor

JTextPane example

JTextPane 을 이용한 텍스트에 스타일 적용하는 예


JTextPane 은 JEditorPane 을 상속하여 생성한 클래스이므로 HTML 코드를 화면에 출력할 수 있으며 링크를 표현할 수 있으며 링크를 클릭하면 이벤트 핸들러를 통해 특정 로직을 실행하게 할 수도 있다. 또, 텍스트에 다양한 스타일을 적용할 수 있으므로 텍스트의 색상, 배경색, 밑줄 등 여러가지 스타일을 화면에 표시할 수 있다

HypelinkEvent 를 통해 아래처럼 href 속성값을 리턴 받을 수 있다

e.getURL(); // a 태그의 href 속성 값을 java.net.URL 오브젝트로 리턴한다

e.getDescription(); // a 태그의 href 속성 값을 String 형태로 리턴한다

<a href="download:file_name">다운로드</a> 와 같이 href 속성에 임의의 문자열을 설정하면 getURL(), getDescription()을 통해 리턴된다

package org.kdea.swing;

import java.awt.*;
import java.io.IOException;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class TextPaneTest extends JFrame {

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

	Container contentPane;
	JTextPane textPane;
	
	public TextPaneTest() {
		super("TextPaneTest Test");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setBounds(100, 50, 500, 500);
		contentPane = getContentPane();
		
		textPane = new JTextPane();
		textPane.setContentType("text/html");
		textPane.setEditable(false);
		//textPane.setOpaque(false); // 불투명-false (투명)
		textPane.setBackground(Color.WHITE);
		
		contentPane.add(textPane, BorderLayout.CENTER);
		
		textPane.setText("<a href=\"\">Google</a>");

		StyledDocument doc = textPane.getStyledDocument();
		SimpleAttributeSet styleSet = new SimpleAttributeSet();
		StyleConstants.setForeground(styleSet, Color.RED); 	// 전경색 지정
		StyleConstants.setBackground(styleSet, Color.YELLOW);	//배경색 지정
		StyleConstants.setBold(styleSet, true);		//폰트 스타일
		StyleConstants.setUnderline(styleSet, true); // 텍스트 밑줄
		
		try {
			doc.insertString(doc.getLength(), "\n새로운 문자열", styleSet);
		} catch (BadLocationException e1) {
			e1.printStackTrace();
		}
		textPane.addHyperlinkListener(new HyperlinkListener() {
			@Override
			public void hyperlinkUpdate(HyperlinkEvent e) {
				if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
					System.out.println("링크 클릭함");
					//새로운 HTML요소나 링크를 추가하는 예
				    HTMLEditorKit kit = new HTMLEditorKit();
				    HTMLDocument doc = new HTMLDocument();
				    textPane.setEditorKit(kit);
				    textPane.setDocument(doc);
				    try {
				    	kit.insertHTML(doc, doc.getLength(), "<a href=\"download\">새로운 링크</a>", 0, 0, null);
						kit.insertHTML(doc, doc.getLength(), "<b>hello", 0, 0, HTML.Tag.B);
						kit.insertHTML(doc, doc.getLength(), "<font color='red'><u>world</u></font>", 0, 0, null);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				    
			    }
			}
		});
		
		setVisible(true);
	}
}