001 // License: GPL. For details, see LICENSE file.
002 package org.openstreetmap.josm.gui.widgets;
003
004 import java.awt.BorderLayout;
005 import java.awt.Font;
006 import java.text.MessageFormat;
007
008 import javax.swing.JEditorPane;
009 import javax.swing.JPanel;
010 import javax.swing.UIManager;
011 import javax.swing.text.html.HTMLEditorKit;
012 import javax.swing.text.html.StyleSheet;
013
014 /**
015 * This panel can be used to display larger sections of formatted text in
016 * HTML.
017 *
018 * It displays HTML text in the same font as {@link JLabel}. Hyperlinks are rendered in
019 * blue and they are underlined. There is also a CSS rule for the HTML tag <strong>
020 * configured.
021 *
022 */
023 public class HtmlPanel extends JPanel {
024 private JEditorPane jepMessage;
025
026 protected void build() {
027 setLayout(new BorderLayout());
028 jepMessage = new JEditorPane("text/html", "");
029 jepMessage.setOpaque(false);
030 jepMessage.setEditable(false);
031 Font f = UIManager.getFont("Label.font");
032 StyleSheet ss = new StyleSheet();
033 String rule = MessageFormat.format(
034 "font-family: ''{0}'';font-size: {1,number}pt; font-weight: {2}; font-style: {3}",
035 f.getName(),
036 f.getSize(),
037 f.isBold() ? "bold" : "normal",
038 f.isItalic() ? "italic" : "normal"
039 );
040 rule = "body {" + rule + "}";
041 rule = MessageFormat.format(
042 "font-family: ''{0}'';font-size: {1,number}pt; font-weight: {2}; font-style: {3}",
043 f.getName(),
044 f.getSize(),
045 "bold",
046 f.isItalic() ? "italic" : "normal"
047 );
048 rule = "strong {" + rule + "}";
049 ss.addRule(rule);
050 ss.addRule("a {text-decoration: underline; color: blue}");
051 ss.addRule("ul {margin-left: 1cm; list-style-type: disc}");
052 HTMLEditorKit kit = new HTMLEditorKit();
053 kit.setStyleSheet(ss);
054 jepMessage.setEditorKit(kit);
055
056 add(jepMessage, BorderLayout.CENTER);
057 }
058
059 public HtmlPanel() {
060 build();
061 }
062
063 public HtmlPanel(String text) {
064 this();
065 setText(text);
066 }
067
068 /**
069 * Replies the editor pane used internally to render the HTML text.
070 *
071 * @return the editor pane used internally to render the HTML text.
072 */
073 public JEditorPane getEditorPane() {
074 return jepMessage;
075 }
076
077 /**
078 * Sets the current text to display. <code>text</code> is a html fragment.
079 * If null, empty string is assumed.
080 *
081 * @param text the text to display
082 */
083 public void setText(String text) {
084 if (text == null) {
085 text = "";
086 }
087 jepMessage.setText(text);
088 }
089 }