Java – how to set the direction of jtextarea from right to left (in joptionpane)
I have JScrollPane and jtextarea. I try to set the direction of jtextarea from right to left, so the text will start from the right and the scroll bar will be on the left
I tried the following methods, but did not affect the direction:
txt.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); txt.setAlignmentX(JTextArea.RIGHT_ALIGNMENT);
Edit:
Two answers camickr & spam offers work well, but not in my program. I use my jtextarea as an object message and pass it to optionpane
EDIT2:
I came up with setcomponentorientation (componentorientation. Right_to_left); It doesn't work if I apply it to joptionpane content Is there an alternative solution to this problem?
Similar to my code:
import java.awt.*; import java.util.*; import javax.swing.*; public class TextArea extends JPanel { private JTextArea txt = new JTextArea(); public TextArea() { setLayout(new GridLayout()); txt.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); JScrollPane scroll = new JScrollPane(txt); scroll.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); setPreferredSize(new Dimension(200,200)); this.add(scroll); } private void display() { Object[] options = {this}; JOptionPane pane = new JOptionPane(); int option = pane.showOptionDialog(null,null,"Title",JOptionPane.DEFAULT_OPTION,JOptionPane.PLAIN_MESSAGE,options,options[0]); } public static void main(String[] args) { new TextArea().display(); } }
Solution
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The text starts on the right, but is still appended to the end when entering, rather than the beginning of the inserted line
to update:
I don't know why it doesn't work in the options pane This is a simple solution:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; public class Test { public static void main(String args[]) throws Exception { SwingUtilities.invokelater(new Runnable() { public void run() { JTextArea textArea = new JTextArea(4,20); JScrollPane scrollPane = new JScrollPane( textArea ); JPanel panel = new JPanel(); panel.add( scrollPane ); scrollPane.addAncestorListener( new AncestorListener() { public void ancestorAdded(AncestorEvent e) { JScrollPane scrollPane = (JScrollPane)e.getComponent(); scrollPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } public void ancestorMoved(AncestorEvent e) {} public void ancestorRemoved(AncestorEvent e) {} }); JOptionPane.showMessageDialog(null,panel); } }); } }