Pit*_*elk 3 java swing jtextpane caret jtextarea
我偶然发现了以下问题:
我想在组件的插入符号的位置读取JTextComponent文档中的字符.当我使用JTextPane时,在插入符号位置返回的字符不正确.更详细地说,返回的字符是字符是插入符号的位置减去行的数量!(插入位置 - 当前行的编号).另一方面,当我使用JTextArea时,结果是正确的......为了证明这一点,我已经实现了一个可以使用的示例程序.
所以最大的问题是,在JTextPane的情况下,如何获得插入符号的位置?
为什么JTextPane不会返回与JTextArea相同的插入位置,还有更多为什么JTextPane返回的字符不是我们在屏幕上看到的字符?描述的行为是错误的吗?
您可以在下面找到示例程序的代码以及非常有趣和意外结果的屏幕截图
使用JTextPane.CARET职位17中的字母是e.不...
alt text http://img405.imageshack.us/img405/2746/jtextpane.jpg
使用JTextArea.在这里,我的插入符号与之前的位置相同,但现在我得到插入位置20,返回字母是\ r \n(与预期的一个).
alt text http://img809.imageshack.us/img809/5323/jtextarea.jpg
以下是您可以使用的代码来查看这种奇怪的行为:
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
PS我正在使用java 6.
使用
char result = testingArea.getDocument().getText(caretPosition,1).charAt(0);
Run Code Online (Sandbox Code Playgroud)
而不是
char result = testingArea.getText().charAt(caretPosition);
Run Code Online (Sandbox Code Playgroud)
我认为在JTextPane中EOL算作一个字符(\n我想),而在JTextArea中它被算作两个(\ r \n).
Oracle文档说:
JEditorPane类是Swing样式文本组件的基础,并提供了一种机制,您可以通过该机制添加对自定义文本格式的支持.如果您想要无样式文本,请改用文本区域.
因此,文本区域仅基于给定文本,因此所有条目字符都是计数.JEditorPane使用StyledDocument,因此可能会解释EOL.