Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text and a JComponent in a JTextPane vertically?

Currently it looks so

enter image description here

What to do so that it looks so?

enter image description here

Below is my code:

    JFrame f = new JFrame();
    JTextPane textPane = new JTextPane();

    JTextField component = new JTextField("      ");
    component.setMaximumSize(component.getPreferredSize());
    textPane.setSelectionStart(textPane.getDocument().getLength());
    textPane.setSelectionEnd(textPane.getDocument().getLength());
    textPane.insertComponent(component);
    try {
        textPane.getDocument().insertString(textPane.getDocument().getLength(), "text",
            new SimpleAttributeSet());
    } catch (BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    f.add(new JScrollPane(textPane));
    f.setSize(200, 100);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

The single question which is near to this topic I found: JTextPane insert component, faulty vertical alignment But there is no answer how to change the alignment. But it must be possible according to the discussion there.

like image 219
ka3ak Avatar asked Jan 14 '23 17:01

ka3ak


1 Answers

You can use this http://java-sl.com/tip_center_vertically.html

It should work with JComponents as well.

You can also override LabelView's getPreferredSpan() adding some space to the bottom.

Alternatively you can try to override RowView inner class in ParagraphView

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/text/ParagraphView.java#ParagraphView.Row

That points to inner class Row extends BoxView

You should replace it with own one. Try to override

public float getAlignment(int axis) 

to return CENTER (0.5). If this does not help override layoutMinorAxis(0 to return proper offsets (shifted).

like image 65
StanislavL Avatar answered Jan 23 '23 01:01

StanislavL