Swing/JEditorPane HyperLink

HyperLink in JEditorPane

Soul-Learner 2014. 5. 29. 14:33

Java Swing 콤포넌트 중의 JEditorPane 를 이용한 링크 기능 예제

JEditorPane내의 텍스트에 Hyper Link를 설정하고 마우스로 링크를 클릭했을 때 발생하는 이벤트로부터 클릭된 문자열을 추출하는 예이다


public static void main(String args[]) {


      java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                MainFrame mf = new MainFrame(); // JFrame을 상속한 클래스


                JEditorPane editorPane = new JEditorPane();

                editorPane.setEditable(false);

                editorPane.setBounds(100,100,200,100);

                editorPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));

                editorPane.setText("<html><body>링크를 테스트합니다<br>"+

                        "우측의 링크를 눌러보세요. <a href=\"http://click\">CLICK</a><br>"+

                        "클릭하면 이벤트 핸들러가 실행되는 것을 확인해보세요</body></html>");

                editorPane.addHyperlinkListener(new HyperlinkListener() {


                    @Override

                    public void hyperlinkUpdate(HyperlinkEvent e) {

                        HyperlinkEvent.EventType type = e.getEventType();

                        if(type==HyperlinkEvent.EventType.ACTIVATED) {

                            System.out.println(e.getURL().toString()); // http://click 출력됨

                        }

                    }

                });


                mf.getContentPane().add(editorPane); // 프레임에 JEditorPane 추가

                mf.setVisible(true);// 화면에 출력

            }

        });

    }