Java Swing How to - Apply ForegroundActions in a JEditorPane when reading HTML








Question

We would like to know how to apply ForegroundActions in a JEditorPane when reading HTML.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
/*ww w  .j  a  v  a 2  s . c o  m*/
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLEditorKit;

public class Main extends JFrame {

  public Main() {
    JEditorPane editorPane = new JEditorPane();
    editorPane.setContentType("text/HTML");
    editorPane.setEditorKit(new HTMLEditorKit());
    editorPane.setText("<hr>Welcome to <b>java2s.com!</b><hr>");
    JToolBar bar = new JToolBar();
    bar.add(new StyledEditorKit.ForegroundAction("Red", Color.red));
    bar.add(new StyledEditorKit.ForegroundAction("Blue", Color.blue));
    bar.add(new StyledEditorKit.FontSizeAction("12", 12));
    bar.add(new StyledEditorKit.FontSizeAction("14", 14));
    bar.add(new StyledEditorKit.FontSizeAction("16", 16));
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.add(bar, BorderLayout.NORTH);
    this.add(editorPane, BorderLayout.CENTER);
    this.pack();
    this.setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }
}