How to add JLabel to JEditorPane?

I am trying to extend the StyledEditorKit in Swing to be able to include JLabel inside the editor. I was able to do this, and this is what I got so far. In the image below, the highlighted text button is of type JLabel, while the rest of the text is plain text.

enter image description here

As you can see, the label looks a little lower than the plain text. How to align the top of the top of the remaining text?

Here is the view code that is used to create this label element:

class ComponentView(Element elem) {
      @Override
      protected Component createComponent() {
        JLabel lbl = new JLabel("");
        lbl.setOpaque(true);
        lbl.setBackground(Color.red);
        try {
               int start = getElement().getStartOffset();
               int end = getElement().getEndOffset();
               String text = getElement().getDocument().getText(start, end - start);
               lbl.setText(text);
         } catch (BadLocationException e) {}
         return lbl;
       }
}
+5
source share
1 answer

Component.getAlignmentY, , ComponentView.

JTextPane, . insertComponent(). , setAlignmentY:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;

public class TextPaneDemo {
    private static void createAndShowGUI() {
        final JTextPane pane = new JTextPane();
        pane.setText("Some text");

        JButton buttonButton = new JButton("Insert label");
        buttonButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                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.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
+5

All Articles