Java 如何在JTextPane中垂直居中文本和JComponent?
现在看来是这样 怎么做才能使它看起来如此 下面是我的代码:Java 如何在JTextPane中垂直居中文本和JComponent?,java,swing,alignment,jtextpane,jcomponent,Java,Swing,Alignment,Jtextpane,Jcomponent,现在看来是这样 怎么做才能使它看起来如此 下面是我的代码: JFrame f = new JFrame(); JTextPane textPane = new JTextPane(); JTextField component = new JTextField(" "); component.setMaximumSize(component.getPreferredSize()); textPane.setSelectionStart(te
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);
我发现了一个与这个主题相近的问题:
但如何改变路线却没有答案。但是根据那里的讨论,这必须是可能的。你可以使用这个
它还应该与JComponents
一起使用
您还可以覆盖LabelView的getPreferredSpan()
在底部添加一些空间
或者,您可以尝试覆盖段落视图中的行视图
内部类
指向内部类行的视图
你应该把它换成自己的。试图覆盖
public float getAlignment(int axis)
返回中心(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"));
根据上述答案(这对我来说不起作用,但帮助我找到了这个答案),我使用了:
这正确对齐了文本“some text”和图标。@DavidKroukamp我认为垂直对齐会影响垂直定位。第二张图片上的文本位置低于第一张图片上的文本。GetPreferedspan()我可以用一个常量值来调整文本位置。但是如果使用不同大小的组件呢?我希望所有的东西看起来都像串肉。虽然肉块可以有不同的大小,但它们都是通过中心串成串的。串肉是文本。这可以用“RowView”和“ParagraphView”来完成吗?如果是这样,我无法理解如何重写一个类,并且ParagraphView中也没有这样的内部类。谢谢!getAlignment()的重写有帮助。@StanislavL感谢
CenteredBoxView
,+1!不过有一个问题,它不应该是textBlockHeight+=spans[I];
在CenteredBoxView.layoutMajorAxis()中,而不是textBlockHeight=span[i];
?
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"))