Вместо использования 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();
}
Вы получите результат, как показано ниже.
![enter image description here](https://i.stack.imgur.com/ZVSbF.png)
Надеюсь, вы получили ответ, который хотите.