It would be very helpful to have a label that can work link HTML A tag. The following child of JLabel have this functionality and the hover color can be customized also.
Download Source
package com.blogspot.codetoearn.linklabel; import java.awt.Color; import java.awt.Cursor; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.Icon; import javax.swing.JLabel; /** * http://codetoearn.blogspot.com/ * * @author ehsun7b */ public class LinkLabel extends JLabel { private String url; private Color hoverColor = Color.blue; private Color forgroundColor; public LinkLabel(String url, String text, Icon icon, int horizontalAlignment) { super(text, icon, horizontalAlignment); this.url = url; init(); } public LinkLabel(String url, String text, int horizontalAlignment) { super(text, horizontalAlignment); this.url = url; init(); } public LinkLabel(String url, String text) { super(text); this.url = url; init(); } public LinkLabel(String url, Icon image, int horizontalAlignment) { super(image, horizontalAlignment); this.url = url; init(); } public LinkLabel(String url, Icon image) { super(image); this.url = url; init(); } public LinkLabel(String url) { this.url = url; init(); } private void init() { addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { openUrl(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { if (forgroundColor == null) { forgroundColor = getForeground(); } setForeground(hoverColor); } @Override public void mouseExited(MouseEvent e) { setForeground(forgroundColor); } }); setCursor(new Cursor(Cursor.HAND_CURSOR)); } private void openUrl() { openURL(url); } public static void openURL(String url) { if (!java.awt.Desktop.isDesktopSupported()) { return; } java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if (!desktop.isSupported(java.awt.Desktop.Action.BROWSE)) { return; } try { java.net.URI uri = new java.net.URI(url); desktop.browse(uri); } catch (URISyntaxException | IOException e) { System.err.println(e.getMessage()); } } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Color getHoverColor() { return hoverColor; } public void setHoverColor(Color hoverColor) { this.hoverColor = hoverColor; } public Color getForgroundColor() { return forgroundColor; } public void setForgroundColor(Color forgroundColor) { this.forgroundColor = forgroundColor; } }
No comments:
Post a Comment