Java 为什么textPane.getDocument().getText()返回空字符串?

Java 为什么textPane.getDocument().getText()返回空字符串?,java,swing,jtextpane,Java,Swing,Jtextpane,如果试图从内容类型为“text/html”的JTextPane组件中获取文本(换行符在其位置上),我在这里做错了什么 textPane.getText()返回HTML,但头和体为空。 textPane.getDocument().getText()返回空字符串 注:在同一代码中,我也没有换行和其他问题,我应该用相同的代码作为独立问题来问它们吗 代码: package test; import java.io.IOException; import java.io.StringReader; i

如果试图从内容类型为“text/html”的JTextPane组件中获取文本(换行符在其位置上),我在这里做错了什么

textPane.getText()
返回HTML,但头和体为空。
textPane.getDocument().getText()
返回空字符串

注:在同一代码中,我也没有换行和其他问题,我应该用相同的代码作为独立问题来问它们吗

代码:

package test;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
//import javax.swing.text.StyledEditorKit;

public class TextPaneTester extends javax.swing.JFrame {

    public TextPaneTester() {
        initComponents();
        myInitComponents();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        contentScrollPane = new javax.swing.JScrollPane();
        content = new javax.swing.JTextPane();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        contentScrollPane.setViewportView(content);

        // layout code by NetBeans
    }// </editor-fold>                        

    private void myInitComponents(){
        //content.setEditorKit(new StyledEditorKit());
        contentScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        contentScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }

    private void fetchURL(String url){
        try{
            // URL(URL baseURL[, String relativeURL])
            URL helpURL = new URL(url);
            System.out.println(helpURL);
            this.content.setPage(helpURL);

            try {
                System.out.println("This far!");
                //System.out.println(this.content.getDocument());
                System.out.println("getDocument() on JTextPane gives " + this.content.getDocument());
                System.out.println("getText() on JTextPane gives " + this.content.getText());

                // Why this line retuens an empty string?
                String text = this.content.getDocument().getText(0, this.content.getDocument().getLength());
                System.out.println("getDocument.getText() on JTextPane gives " + text);

                System.out.println("This far 2!");
                // this.translation.setPage(helpURL);
            } catch (BadLocationException ex) {
                System.out.println("Why this far!");
                Logger.getLogger(TextPaneTester.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + url);
        }
        // return this.content;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                String url = "https://en.wikipedia.org/wiki/Virtaal";
                TextPaneTester reader = new TextPaneTester();
                reader.fetchURL(url);
                reader.setVisible(true);
            }
        });
    }

    private javax.swing.JTextPane content;
    private javax.swing.JScrollPane contentScrollPane;
    // End of variables declaration                   
}
run:
https://en.wikipedia.org/wiki/Virtaal
This far!
getDocument() on JTextPane gives javax.swing.text.html.HTMLDocument@1767743f
getText() on JTextPane gives <html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">

    </p>
  </body>
</html>

getDocument.getText() on JTextPane gives 
This far 2!
<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">

    </p>
  </body>
</html>

Let's see what the parser gives: 
BUILD SUCCESSFUL (total time: 55 seconds)
封装测试;
导入java.io.IOException;
导入java.io.StringReader;
导入java.net.URL;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.JScrollPane;
导入javax.swing.text.BadLocationException;
//导入javax.swing.text.StyledEditorKit;
公共类TextPaneTester扩展了javax.swing.JFrame{
public TextPaneTester(){
初始化组件();
myInitComponents();
}
//                           
私有组件(){
contentScrollPane=newjavax.swing.JScrollPane();
content=newjavax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
contentScrollPane.setViewportView(内容);
//NetBeans的布局代码
}//                         
私有void myInitComponents(){
//setEditorKit(新的StyledEditorKit());
contentScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL\u SCROLLBAR\u ALWAYS);
contentScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HorizontalScrollBar\uNever);
}
私有void fetchURL(字符串url){
试一试{
//URL(URL baseURL[,字符串相对值])
URL helpURL=新URL(URL);
System.out.println(helpURL);
this.content.setPage(helpURL);
试一试{
System.out.println(“到此为止!”);
//System.out.println(this.content.getDocument());
System.out.println(“JTextPane上的getDocument()给出”+this.content.getDocument());
System.out.println(“JTextPane上的getText()给出“+this.content.getText());
//为什么这行复述空字符串?
String text=this.content.getDocument().getText(0,this.content.getDocument().getLength());
System.out.println(“JTextPane上的getDocument.getText()给出“+text”);
System.out.println(“ThisFar2!”);
//this.translation.setPage(helpURL);
}捕获(BadLocationException ex){
System.out.println(“为什么这么远!”);
Logger.getLogger(TextPaneTester.class.getName()).log(Level.SEVERE,null,ex);
}
}
捕获(IOE异常){
System.err.println(“试图读取错误的URL:+URL”);
}
//返回此.content;
}
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}
//
/*创建并显示表单*/
invokeLater(new Runnable()){
@凌驾
公开募捐{
字符串url=”https://en.wikipedia.org/wiki/Virtaal";
TextPaneTester reader=newtextpanetester();
reader.fetchURL(url);
reader.setVisible(true);
}
});
}
私有javax.swing.JTextPane内容;
私有javax.swing.JScrollPane内容滚动窗格;
//变量结束声明
}
输出:

package test;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
//import javax.swing.text.StyledEditorKit;

public class TextPaneTester extends javax.swing.JFrame {

    public TextPaneTester() {
        initComponents();
        myInitComponents();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        contentScrollPane = new javax.swing.JScrollPane();
        content = new javax.swing.JTextPane();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        contentScrollPane.setViewportView(content);

        // layout code by NetBeans
    }// </editor-fold>                        

    private void myInitComponents(){
        //content.setEditorKit(new StyledEditorKit());
        contentScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        contentScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }

    private void fetchURL(String url){
        try{
            // URL(URL baseURL[, String relativeURL])
            URL helpURL = new URL(url);
            System.out.println(helpURL);
            this.content.setPage(helpURL);

            try {
                System.out.println("This far!");
                //System.out.println(this.content.getDocument());
                System.out.println("getDocument() on JTextPane gives " + this.content.getDocument());
                System.out.println("getText() on JTextPane gives " + this.content.getText());

                // Why this line retuens an empty string?
                String text = this.content.getDocument().getText(0, this.content.getDocument().getLength());
                System.out.println("getDocument.getText() on JTextPane gives " + text);

                System.out.println("This far 2!");
                // this.translation.setPage(helpURL);
            } catch (BadLocationException ex) {
                System.out.println("Why this far!");
                Logger.getLogger(TextPaneTester.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + url);
        }
        // return this.content;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TextPaneTester.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                String url = "https://en.wikipedia.org/wiki/Virtaal";
                TextPaneTester reader = new TextPaneTester();
                reader.fetchURL(url);
                reader.setVisible(true);
            }
        });
    }

    private javax.swing.JTextPane content;
    private javax.swing.JScrollPane contentScrollPane;
    // End of variables declaration                   
}
run:
https://en.wikipedia.org/wiki/Virtaal
This far!
getDocument() on JTextPane gives javax.swing.text.html.HTMLDocument@1767743f
getText() on JTextPane gives <html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">

    </p>
  </body>
</html>

getDocument.getText() on JTextPane gives 
This far 2!
<html>
  <head>

  </head>
  <body>
    <p style="margin-top: 0">

    </p>
  </body>
</html>

Let's see what the parser gives: 
BUILD SUCCESSFUL (total time: 55 seconds)
运行:
https://en.wikipedia.org/wiki/Virtaal
这么远!
JTextPane上的getDocument()提供javax.swing.text.html。HTMLDocument@1767743f
JTextPane上的getText()提供

JTextPane上的getDocument.getText()提供 这么远!

让我们看看解析器给出了什么: 构建成功(总时间:55秒)
与往常一样,您应该首先查看:

如果以异步方式加载文档,则将使用调用
setDocument
立即将文档安装到编辑器中,该调用将触发文档属性更改事件,然后将创建一个线程,该线程将开始实际加载。在这种情况下,调用此方法不会直接触发页面属性更改事件,而是在执行加载的线程完成后触发。它还将在事件分派线程上激发。