2010-11-08 15 views
1

下面的代碼片斷有問題,如果在包含小程序窗口的瀏覽器中按下重新加載按鈕,它將無法正常工作。它適用於小程序的第一次啓動,但不在重新加載。 AppletViewer中也會發生同樣的事情。奇怪的HTMLEditorKit問題

原因是,Text.setText(...)調用在HTMLParser內深深地陷入了NullPointerException。我已經嘗試將setText調用放入start(),但這沒有幫助。

您是否知道任何解決方法?謝謝你的幫助。 RG

@Override 
public void init() 
{ 
    //Execute a job on the event-dispatching thread: 
    //creating this applet's GUI. 
    try 
    { 
     javax.swing.SwingUtilities.invokeAndWait(new Runnable() { 
      public void run() { 
       createGUI(); 
      } 
     }); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     System.err.println("createGUI didn't successfully complete"); 
    } 
} 

private void createGUI() 
{ 
    ((JComponent)this.getContentPane()).setBorder(new CompoundBorder 
      (BorderFactory.createRaisedBevelBorder(), 
        new EmptyBorder(5,5,5,5))); 

    BorderLayout bl=new BorderLayout(); 
    bl.setVgap(5); 
    setLayout(bl); 

    Input=new JTextField(); 
    Input.setFont(new Font("arial",Font.PLAIN,14)); 
    add("North",Input); 
    Input.addActionListener(this); 

    HTMLEditorKit kit=new HTMLEditorKit(); 
    Text=new JTextPane(); 
    Text.setFont(new Font("arial",Font.PLAIN,14)); 
    Text.setEditorKit(kit); 
    Text.setText("<p>Test</p>"); 
    Text.setEditable(false); 
    Text.setBackground(Color.white); 
    add("Center",new JScrollPane(Text)); 

} 

回答

1

不確定從哪裏複製了代碼,但它看起來非常老。

add("North",Input); 
add("Center",new JScrollPane(Text)); 

這不是在將組件添加到容器時指定約束的首選方法。閱讀API以獲得推薦的方法。或者閱讀「如何使用邊界佈局」的Swing教程以獲取示例。

不確定爲什麼要創建編輯器工具包。此外,您的文本是不正確的HTML(不知道它是否有所作爲)。

我只是用這樣的代碼在過去的以下內容:

String text = "<html><body>Some text><body></html>"; 
JEditorPane editor = new JEditorPane("text/html", text); 

我也覺得它更容易使用的JTextPane,然後如果你需要樣式化文本中使用屬性。

+0

感謝您的回答!是的佈局代碼是老式的,但它仍然有效,這不是問題。我嘗試了沒有HTMLEditorKit的JEditorPane方法,這似乎是相同的,但更容易。但是,applet在重新加載後仍然崩潰,在HTML解析器中遇到同樣的問題。如果我使用普通文本,我可以隨時重新加載,只要我喜歡。 – Rene 2010-11-08 20:42:23

+0

不,缺少html和body標籤沒有任何區別。 – Rene 2010-11-08 20:43:10

+0

感謝您的幫助,我發現它是:這是一個bug請參閱http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6993691 – Rene 2010-11-08 20:44:17