Java Swing How to - Set Font Size of selected text in JEditorPane Using JComboBox








Question

We would like to know how to set Font Size of selected text in JEditorPane Using JComboBox.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
/*w  ww.  ja va 2  s.  c  o  m*/
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;

public class Main extends JPanel {
  Integer[] ITEMS = { 9, 10, 11, 12, 14, 16, 18, 20, 24, 32 };
  JEditorPane editorPane = new JEditorPane();
  JComboBox<Integer> fontBox = new JComboBox<Integer>(ITEMS);
  StyledDocument doc = new DefaultStyledDocument();
  StyledEditorKit styledEditorKit = new StyledEditorKit();

  public Main() {
    editorPane.setDocument(doc);
    editorPane.setEditorKit(styledEditorKit);
    JScrollPane scrollpane = new JScrollPane(editorPane);
    scrollpane.setPreferredSize(new Dimension(500, 400));
    JPanel comboPanel = new JPanel();
    comboPanel.add(fontBox);

    setLayout(new BorderLayout());
    add(scrollpane, BorderLayout.CENTER);
    add(comboPanel, BorderLayout.SOUTH);

    Document doc = editorPane.getDocument();
    for (int i = 0; i < 20; i++) {
      int offset = doc.getLength();
      String str = "This is line number: " + i + "\n";
      try {
        doc.insertString(offset, str, null);
      } catch (BadLocationException e) {
        e.printStackTrace();
      }
    }

    fontBox.addActionListener(e -> {
      int size = (Integer) fontBox.getSelectedItem();
      Action fontAction = new StyledEditorKit.FontSizeAction(String
          .valueOf(size), size);
      fontAction.actionPerformed(e);
    });
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new Main());
    frame.pack();
     frame.setVisible(true);
  }
}