我目前正在用 Java 编写一个消息程序。我有一个用于输入消息的框,另一个框是在我发送消息并收到回复后出现的。第二个框是 JText Area,我想知道如何让我的消息显示在框的右侧,而响应显示在左侧(如 iMessage)。我似乎找不到如何相应地在 jTextArea 中定位字符串。
最佳答案
不要使用 JTextArea
,而是尝试使用 JTextPane
,如下所示。
JTextPane textPane = new JTextPane();
frame.getContentPane().add(textPane, BorderLayout.CENTER);
textPane.setContentType("text/html");
textPane.setEditable(false);
创建JTextPane
后添加如下样式。
StyledDocument doc=textPane.getStyledDocument();
SimpleAttributeSet right =new SimpleAttributeSet();
SimpleAttributeSet left =new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
现在将文本添加到 JTextPane
try {
doc.insertString(0, "First Line aligned left\n", left);
doc.insertString(doc.getLength(), "Second line Aligned right\n", right);
} catch (Exception e) {
e.printStackTrace();
}
您将得到如下结果。
希望您能得到您想要的答案。
关于java - 将 JText 区域一分为二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160497/