001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.ui.factory;
020
021import org.jdom2.Element;
022import org.jpos.ui.UI;
023import org.jpos.ui.UIFactory;
024
025import javax.swing.*;
026import javax.swing.event.HyperlinkEvent;
027import javax.swing.event.HyperlinkListener;
028import javax.swing.text.html.HTMLDocument;
029import javax.swing.text.html.HTMLFrameHyperlinkEvent;
030
031/**
032 * @author Alejandro Revilla
033 *
034 * Creates an html browser/editor
035 * i.e:
036 * <pre>
037 *  &lt;html editable="false" follow-links="true" scrollable="true"&gt;
038 *    http://jpos.org
039 *  &lt;/html&gt;
040 * </pre>
041 * @see org.jpos.ui.UIFactory
042 */
043public class HtmlFactory implements UIFactory {
044    public JComponent create (UI ui, Element e) {
045        try {
046            JEditorPane editorPane = new JEditorPane (e.getText());
047            editorPane.setEditable (
048                "true".equals (e.getAttributeValue ("editable"))
049            );
050            if ("true".equals (e.getAttributeValue ("follow-links")))
051                editorPane.addHyperlinkListener (new Listener ());
052            return editorPane;
053        } catch (Exception ex) {
054            return new JLabel (ex.getMessage());
055        }
056    }
057    static class Listener implements HyperlinkListener {
058        public void hyperlinkUpdate(HyperlinkEvent e) {
059            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
060                JEditorPane pane = (JEditorPane) e.getSource();
061                if (e instanceof HTMLFrameHyperlinkEvent) {
062                    HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
063                    HTMLDocument doc = (HTMLDocument)pane.getDocument();
064                    doc.processHTMLFrameHyperlinkEvent(evt);
065                } else {
066                    try {
067                        pane.setPage(e.getURL());
068                    } catch (Throwable t) {
069                        t.printStackTrace();
070                    }
071                }
072            }
073        }
074    }
075}
076