簡體   English   中英

JTextPane中的插入符位置不正確嗎? 錯誤或預期行為?

[英]Caret position in JTextPane is not correct ?! Bug or expected behavior?

我偶然發現了以下問題:

我想在組件的插入符位置讀取JTextComponent文檔中的字符。 當我使用JTextPane時,在插入符號位置返回的字符不是正確的字符。 更詳細地講,返回的字符是字符,即插入號的位置減去行號!!! (脫字符位置-當前行號)。 另一方面,當我使用JTextArea時,結果是正確的。為了證明這一點,我實現了一個示例程序,您可以使用它。

因此,最大的問題是,在使用JTextPane的情況下,如何獲得插入符號的位置字符?

為什么JTextPane不返回與JTextArea相同的插入符號位置,並且為什么JTextPane返回的字符不是我們在屏幕上看到的字符呢? 描述的行為是錯誤嗎?

在下面,您可以找到示例程序的代碼以及非常有趣和意外的結果的屏幕截圖。

使用JTextPane。 CARET位置17中的字母是e。 不...

替代文字

Usign一個JTextArea 在這里,我的插入符號的位置與以前相同,但是現在我的插入符號的位置為20,返回字母為\\ r \\ n(預期的是)。

替代文字

這是您可以用來查看這種奇怪行為的代碼:

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);

        }
    });
}
}

謝謝您的幫助!

PS我正在使用Java 6。

使用

char result = testingArea.getDocument().getText(caretPosition,1).charAt(0);

而不是

char result = testingArea.getText().charAt(caretPosition);

我認為在JTextPane中,EOL被視為一個字符(\\ n我想是),而在JTextArea中,它被視為兩個字符(\\ r \\ n)。

Oracle文檔說:

JEdi​​torPane類是Swing樣式文本組件的基礎,並提供了一種機制,您可以通過該機制添加對自定義文本格式的支持。 如果要使用無樣式的文本,請改用文本區域。

因此,文本區域僅基於給定的文本,因此所有輸入字符都被計數。 JEdi​​torPane使用了StyledDocument,因此可以解釋EOL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM