package net.oni2.swingcomponents; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; import java.io.IOException; import java.net.URISyntaxException; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.UIDefaults; import javax.swing.border.Border; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.DefaultCaret; import javax.swing.text.html.CSS; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; /** * @author Christian Illy */ public class HTMLLinkLabel extends JEditorPane { private static final long serialVersionUID = 2416829757362043910L; private String prefix; private String suffix; private boolean borderEnabled = true; /** * Create a new HTMLLinkLabel */ public HTMLLinkLabel() { super(); ((DefaultCaret) this.getCaret()) .setUpdatePolicy(DefaultCaret.NEVER_UPDATE); setContentType("text/html"); Font font = new JLabel().getFont(); StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); style.append("font-size:" + font.getSize() + "pt;"); style.append("margin: 0; padding: 0;"); prefix = ""; suffix = ""; addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); setEditable(false); Color bgColor = ColorCopy.copyColor(new JFrame().getBackground()); UIDefaults defaults = new UIDefaults(); defaults.put("EditorPane[Enabled].backgroundPainter", bgColor); putClientProperty("Nimbus.Overrides", defaults); putClientProperty("Nimbus.Overrides.InheritDefaults", true); setBackground(bgColor); } /** * Add or reset a CSS attribute for styling the text * * @param selector * CSS selector * @param attribute * CSS attribute * @param value * Value */ public void setCssAttribute(String selector, CSS.Attribute attribute, String value) { HTMLEditorKit hek = (HTMLEditorKit) getEditorKit(); StyleSheet css = hek.getStyleSheet(); css.addRule(String.format("%s {%s: %s}", selector, attribute.toString(), value)); } /** * Allow or forbid to set a non-null border * * @param enable * Non-null border allowed? */ public void enableBorder(boolean enable) { this.borderEnabled = enable; if (!enable) setBorder(null); } @Override public void setBorder(Border border) { if (borderEnabled || border == null) super.setBorder(border); } @Override public void setText(String t) { if (t.startsWith("

")) t = t.replaceFirst("

", "

"); super.setText(prefix + t + suffix); } }