我尝试从右到左水平对齐文本,用于linecounter textarea,但是它工作但是我遇到了垂直文本对齐的问题,它没有与textEditor行正确对齐。
下面是它的外观和完整代码的截图:
正如您所看到的,从左到右,行计数器的文本区域与textEditor textarea在一行,但是当我为行计数器从右向左改变方向时,它不在同一行。
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();
}
});
}
}
那么,是否有其他方法或修复方法可以将此文本从右向左对齐以用于行计数器?