2015-02-07 39 views
0

我有一個JTextField,我需要在文本字段中編輯或添加新內容。能夠在使用文檔偵聽器之後獲取文本,但無法設置文本。它拋出像如何使用文檔偵聽器將文本設置爲標題?

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: 
    Attempt to mutate in notification 

錯誤我的代碼:

t_pageno.getDocument().addDocumentListener(new DocumentListener() { 
    @Override 
    public void changedUpdate(DocumentEvent e) { 
     warn(); 
    } 

    @Override 
    public void removeUpdate(DocumentEvent e) { 
     warn(); 
    } 

    @Override 
    public void insertUpdate(DocumentEvent e) { 
     warn(); 
    } 

    public void warn() { 
     if (
       Integer.parseInt(t_pageno.getText()) > Integer.parseInt(Config.maxpageno) 
       && 
       Integer.parseInt(t_pageno.getText()) < 0 
       ) { 
      JOptionPane.showMessageDialog(null, 
        "Error: Please enter number bigger than 0 and less than "+Config.maxpageno, "Error Massage", 
        JOptionPane.ERROR_MESSAGE); 
     } 
     else 
     { 
     String pageno = t_pageno.getText(); 
      if (!pageno.equals(new File(Current_index).getName().substring(18, 20))) { 
       int Storyidconfirm = JOptionPane.showConfirmDialog(null, "Do You want to change the Page No", "Change PageNo", JOptionPane.YES_NO_OPTION); 
       if (Storyidconfirm == JOptionPane.YES_OPTION) { 
        String newidchange = new File(Current_index).getName().substring(0, 18) + pageno + new File(Current_index).getName().substring(21, new File(Current_index).getName().length()); 
        JOptionPane.showMessageDialog(null, "Change in page no ??????????"); 
       } 
       else 
       { 
        JOptionPane.showMessageDialog(null, "Reversing to old page no"); 
        JOptionPane.showMessageDialog(null, "new File(Current_index).getName().substring(18, 20) --> "+new File(Current_index).getName().substring(18, 20)); 
        t_pageno.setText(new File(Current_index).getName().substring(18, 20).toString());        
       } 
     } 
     } 
     } 
}); 

回答

2

DocumentListener不嘗試做修改到Document,當它被通知的好地方,在Document在狀態突變,所以任何嘗試進一步修改它將導致它拋出一個IllegalStateException

如果你想改變或過濾文本之前它被提交到Document你應該使用DocumentFilter相反,這是它的設計目的。

請參閱Implementing a Document FilterDocumentFilter Examples瞭解更多詳情。

你應該永遠只能使用DocumentListener當你想被通知更改Document後,他們已經提交到了Document,從不試圖用它來過濾或以其他方式修改Document反正

我也強烈地勸阻你不要在每個更新中顯示一個提示,因爲這隻會令人討厭。相反,我會以某種方式突出顯示該字段,指示該值的值無效(可能會提供更多信息的工具提示)和/或更新某種狀態值/標籤。我可能會考慮使用ActionListener和/或InputVerifier來執行物理驗證,然後向用戶顯示錯誤,以便他們在輸入並更正錯誤之前可能會犯錯,然後才能使更改生效。

我也建議你看看JSpinner

How to Write an Action ListenersValidating InputHow to Use Spinners更多細節

+0

JOptionPane.showMessageDialog(NULL,...,應該由invokeLater的 – mKorbel 2015-02-07 10:14:38

+0

@mKorbel在延遲這種情況下,我會一起避免它,拉起一個'JOptionPane',因爲用戶輸入一個錯誤的字符只是一個痛苦的屁股,並有更好的方式讓用戶知道他們違反了你有什麼規則地方,但那只是我 – MadProgrammer 2015-02-07 10:47:49

相關問題