cdc.ui.swing.widgets.HtmlPanel Maven / Gradle / Ivy
package cdc.ui.swing.widgets;
import java.awt.Desktop;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.event.HyperlinkEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cdc.ui.swing.GridBagConstraintsBuilder;
import cdc.ui.swing.app.ExceptionDialog;
public class HtmlPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(HtmlPanel.class);
private final JEditorPane wPane = new JEditorPane();
private final StringBuilder builder = new StringBuilder();
public HtmlPanel() {
setLayout(new GridBagLayout());
add(wPane,
GridBagConstraintsBuilder.builder()
.gridx(0)
.gridy(0)
.weightx(1.0)
.weighty(1.0)
.fill(GridBagConstraints.BOTH)
.build());
wPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
wPane.setEditable(false);
wPane.setText("TODO");
wPane.addHyperlinkListener(event -> {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
// Do something with e.getURL() here
LOGGER.info("event: " + event.getURL());
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(event.getURL().toURI());
} catch (IOException | URISyntaxException e) {
ExceptionDialog.showExceptionDialog(this, e, "Failed fo open '" + event.getURL() + "'", null);
}
}
}
});
}
public HtmlPanel clear() {
builder.setLength(0);
builder.append("");
return this;
}
public HtmlPanel append(String text) {
builder.append(text);
return this;
}
public HtmlPanel href(URL url,
String title) {
return this.append("")
.append(title)
.append("");
}
public HtmlPanel href(File file,
String title) {
try {
return href(file.toURI().toURL(),
title);
} catch (final MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
public HtmlPanel href(File file) {
return href(file, file.getPath());
}
public void build() {
builder.append("");
wPane.setText(builder.toString());
}
}