make Hyperlink Label in JEditorPane - Java Swing

Java examples for Swing:JEditorPane

Description

make Hyperlink Label in JEditorPane

Demo Code


import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import java.lang.reflect.*;

public class Main{
    public static final boolean SPILL_GUTS = true;
    public static final ArrayList<Exception> ERRORS = new ArrayList<Exception>();
    public static JEditorPane makeHyperlinkLabel(String label) {
        JEditorPane labelPane = new JEditorPane("text/html", label);
        labelPane.setAlignmentX(Component.LEFT_ALIGNMENT);
        labelPane.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        labelPane.setEditable(false);//from  ww  w  .  j av  a2 s. c o  m
        labelPane.setOpaque(false);
        labelPane.setMaximumSize(new Dimension(10000000, labelPane
                .getPreferredSize().height));
        if (label.startsWith("<html>")) {
            labelPane.addHyperlinkListener(new HyperlinkListener() {
                public void hyperlinkUpdate(HyperlinkEvent hle) {
                    if (HyperlinkEvent.EventType.ACTIVATED.equals(hle
                            .getEventType())) {
                        browse(hle.getURL().toString());
                    }
                }
            });
        }
        return (labelPane);
    }
    public static void browse(String url) {
        Desktop desktop = Desktop.getDesktop();

        if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
            try {
                URI uri = new URI(url);
                desktop.browse(uri);
            } catch (Exception e) {
                DownloaderUtils.errorGUI("couldn't browse to page: " + url,
                        e, false);
            }
        }
    }
    public static void errorGUI(String message, Exception e, boolean fatal) {
        String msg = (fatal ? "" : "NON-") + "FATAL ERROR: " + message;
        JOptionPane.showMessageDialog(null, message, "Error",
                JOptionPane.ERROR_MESSAGE);
        addException(msg, e);
        if (fatal)
            System.exit(1);
    }
    private static void addException(String msg, Exception e) {
        ERRORS.add(new Exception(msg, e));
        if (SPILL_GUTS) {
            System.err.println("LOGGER: Exception added");
            e.printStackTrace();
        }
    }
}

Related Tutorials