i have stumbled into the following problem:
I want to read the character in a JTextComponent's document in the location of the component's caret. When i am using a JTextPane the character returned at the caret's position is not the correct one. In more detail the character returned is the character is the position of the caret minus the number of the line!!! (caret Position- number of current line). In the other hand when i use a JTextArea the result is correct... To demonstrate this i have implemented a sample program that you can play with.
So the big question is , how can i get the character of the caret's position in case of JTextPane?
Why JTextPane does not returns the same caret position as JTextArea, and further more why the character returned by JTextPane is not the one that we can see in the screen? Is the described behavior a bug?
Below you can find the code of the sample program as well as screenshots of the very interesting and unexpected results
Using a JTextPane. The letter in the CARET position 17 is e. nope...
Usign a JTextArea. Here i have the caret in the same position as before, but now i get caret position 20 and the return letter is \r\n (with is the one expected).
Here is the code that you can play with to see this strange behavior :
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
public class Example extends JFrame {
// use this instead of JTextPane to see the difference
// JTextComponent testingArea = new JTextArea(5,10);
JTextComponent testingArea = new JTextPane();
JButton button = new JButton("test");
JTextComponent resultArea = new JTextField(20);
public Example() {
initialise();
testingArea.setText("line1\r\nline2\r\nline3\r\nline4");
}
private void initialise() {
testingArea.setPreferredSize(new Dimension(100,100));
setLayout(new FlowLayout());
getContentPane().add(testingArea);
getContentPane().add(new JLabel("answer"));
getContentPane().add(resultArea);
getContentPane().add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int caretPosition = testingArea.getCaretPosition();
char result = testingArea.getText().charAt(caretPosition);
resultArea.setText("Char at caretPosition " + caretPosition + " is " + result);
}catch (Exception e2) {
e2.printStackTrace();
resultArea.setText("ERROR");
}
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
final Example ex = new Example();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ex.pack();
ex.setVisible(true);
}
});
}
}
Thanks for the help!
PS i am using java 6.
Use
char result = testingArea.getDocument().getText(caretPosition,1).charAt(0);
rather than
char result = testingArea.getText().charAt(caretPosition);