I tried to horizontally align text, from right to left, for linecounter textarea, and it worked but then I got a problem with vertical text alignment, it is not aligning properly with a textEditor line.
Below is screenshot of how it looks like and full code:
As you can see, for left to right, text area for line counter is in a line with textEditor textarea, but as I changed orientation right to left for line counter, it is not in the same line.
CODE:
import java.awt.Color;
import java.awt.ComponentOrientation;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Element;
public class LineNumbering extends JFrame {
private static JTextArea jta;
private static JTextArea lines;
public LineNumbering() {
super("Line Numbering Example");
}
public static void createAndShowGUI() {
JFrame frame = new LineNumbering();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jsp = new JScrollPane();
jta = new JTextArea();
lines = new JTextArea("1");
lines.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
lines.setBackground(Color.LIGHT_GRAY);
lines.setEditable(false);
jta.getDocument().addDocumentListener(new DocumentListener() {
public String getText() {
int caretPosition = jta.getDocument().getLength();
Element root = jta.getDocument().getDefaultRootElement();
String text = "1" + System.getProperty("line.separator");
for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
text += i + System.getProperty("line.separator");
}
return text;
}
@Override
public void changedUpdate(DocumentEvent de) {
lines.setText(getText());
}
@Override
public void insertUpdate(DocumentEvent de) {
lines.setText(getText());
}
@Override
public void removeUpdate(DocumentEvent de) {
lines.setText(getText());
}
});
jsp.getViewport().add(jta);
jsp.setRowHeaderView(lines);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(jsp);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
So, is there maybe other way or a fix to align this text from right to left for line counter ?