Reputation: 697
I'm currently programming a messanger program in Java. I have box where I type in my message and another box where it appears after I have sent it and I receive a response. The second box is JText Area and I was wonder how to I make my message appear on the right hand side of the box and the response on the left side (like iMessage). I can't seem to find how to position the strings in the jTextArea accordingly.
Upvotes: 1
Views: 89
Reputation: 374
Instead of using JTextArea
, try to use JTextPane
as below.
JTextPane textPane = new JTextPane();
frame.getContentPane().add(textPane, BorderLayout.CENTER);
textPane.setContentType("text/html");
textPane.setEditable(false);
After creating JTextPane
add styles as below.
StyledDocument doc=textPane.getStyledDocument();
SimpleAttributeSet right =new SimpleAttributeSet();
SimpleAttributeSet left =new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
StyleConstants.setAlignment(left, StyleConstants.ALIGN_LEFT);
Now add texts to the 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();
}
You will get the result as below.
Hope you got the answer you want.
Upvotes: 1