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

谁说胖子不能爱 提交于 2019-12-05 18:09:04

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).

Define a style for your document with a JLabel and set the vertical aligment on it:

Style s = doc.addStyle("icUf", regular);        
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
    JLabel jl = new JLabel(icUf);
    jl.setVerticalAlignment(JLabel.CENTER);
    StyleConstants.setComponent(s, jl);
}

Insert the label:

doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"));

and the text:

doc.insertString(doc.getLength(), " text ", doc.getStyle("bold"));

Based on the answer above (which didn't work for me, but helped me find this), I used:

Style s = doc.addStyle("icUf", regular);        
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
    // create label with icon AND text
    JLabel jl = new JLabel("some text",icUf, SwingConstants.LEFT);
    StyleConstants.setComponent(s, jl);
}
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"))

This properly aligned the text 'some text' and the icon.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!