[英]How to set different JTextArea text alignment per line?
I have a JTextArea in which i want to display messages aligned to right or left, depending on a variable I pass along with the message. 我有一个JTextArea,我想在其中显示向右或向左对齐的消息,具体取决于我传递的消息变量。 Can I do that? 我能这样做吗?
battleLog = new JTextPane(); StyledDocument bL = battleLog.getStyledDocument(); SimpleAttributeSet r = new SimpleAttributeSet(); StyleConstants.setAlignment(r, StyleConstants.ALIGN_RIGHT); try { bL.insertString(bL.getLength(), "test", r); } catch (BadLocationException e1) { e1.printStackTrace(); }
Not with a JTextArea. 没有JTextArea。
You need to use a JTextPane
which supports different text and paragraph attributes. 您需要使用支持不同文本和段落属性的JTextPane
。 An example to CENTER the text: CENTER文本的一个示例:
JTextPane textPane = new JTextPane();
textPane.setText("Line1");
StyledDocument doc = textPane.getStyledDocument();
// Define the attribute you want for the line of text
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
// Add some text to the end of the Document
try
{
int length = doc.getLength();
doc.insertString(doc.getLength(), "\ntest", null);
doc.setParagraphAttributes(length+1, 1, center, false);
}
catch(Exception e) { System.out.println(e);}
if("left".equals(input)){
setAlignmentX(Component.LEFT_ALIGNMENT);
}
Have a try! 试试!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.