如何垂直居中JTextPane中的文本和JComponent?
目前它看起来如此
怎么做它看起来如此?
以下是我的代码:
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);
我发现接近这个主题的单个问题: JTextPane插入组件,错误的垂直对齐但是如何更改对齐没有答案。 但根据那里的讨论,它必须是可能的。
您可以使用此http://java-sl.com/tip_center_vertically.html
它也应该与JComponents
一起使用。
您还可以覆盖LabelView's
getPreferredSpan()
,向底部添加一些空格。
或者,您可以尝试在ParagraphView
覆盖RowView
内部类
这指向内部类Row扩展BoxView
你应该用自己的替换它。 试着改写
public float getAlignment(int axis)
返回CENTER(0.5)。 如果这没有帮助覆盖layoutMinorAxis(0返回正确的偏移量(移位)。
使用JLabel为文档定义样式并在其上设置垂直对齐:
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); }
插入标签:
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"));
和文字:
doc.insertString(doc.getLength(), " text ", doc.getStyle("bold"));
基于上面的答案(这对我不起作用,但帮助我找到了这个),我使用了:
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"))
这使文本“一些文本”和图标正确对齐。