将 JText 区域一分为二
Splitting JText Area into two
我目前正在 Java 编写一个消息程序。我有一个输入消息的框,另一个框在我发送消息并收到回复后出现。第二个框是 JText 区域,我想知道如何让我的消息显示在框的右侧,响应显示在左侧(如 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 区域,我想知道如何让我的消息显示在框的右侧,响应显示在左侧(如 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();
}
您将得到如下结果。
希望您得到想要的答案。