Java Swing How to - Add JLabel to JEditorPane








Question

We would like to know how to add JLabel to JEditorPane.

Answer

import java.awt.BorderLayout;
/*from   w  ww.j av a  2  s.  co m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;

public class Main {
  public static void main(String[] args) {
    final JTextPane pane = new JTextPane();
    pane.setText("Some text");

    JButton buttonButton = new JButton("Insert label");
    buttonButton.addActionListener(e -> {
      JLabel label = new JLabel("label");
      label.setAlignmentY(0.85f);
      pane.insertComponent(label);

    });

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(buttonButton, BorderLayout.SOUTH);
    panel.add(pane, BorderLayout.CENTER);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(panel);
    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}