Re: [J2SE] 有關 javax.swing.JTextField

看板java作者 (非天夜翔)時間17年前 (2008/06/10 09:54), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/5 (看更多)
※ 引述《csihcs (非天夜翔)》之銘言: : 想請問一下各位大大, : 我在一個 Panel 中加了一個 Field, : 要怎麼讓 Field 只能讓使用者輸入文字, : 有限制最大長度的, : 例如:限制長度為 3, : 那使用者只能輸入最多3個字, : 像是 Field 中,輸入了 ABC, : 那他要打 D 的時候,不會出現 ABCD, <<== 這個才是我想要的效果。 : 而不是可以輸入很多,我讀3個字, : 像是使用者輸入 ABCD,而我只讀 ABC。 : 麻煩大大指點迷津。謝謝。 m(_@_)m 聽了 TonyQ 大的解說,做了下面這個動作 JTextField f = new JTextField(); DocListener dl = new DocListener(3); f.getDocument().addDocumentListener(dl); public class DocListener impliments DocumentListener { private final int length; public DocListener(int length) { this.length = length; } public void insertUpdate(DocumentEvent e) { try { Document doc = e.getDocument(); if(doc.getLength() > length) { doc.remove(length,doc.getLength(),null); // 這裡 Compile 會過,但是 Runtim 的時候只要這行被執行到就會出現 // java.lang.IllegalStateException: Attempt to mutate in notification } } catch (BadLocationException ex) {} } public void removeUpdate(DocumentEvent e) {} public void changedUpdate(DocumentEvent e) {} } 想請問各位大大,我該如何在這裡做 doc 的內容修改。 謝謝各位大大的指教。 m(_@_)m -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.104.31.180

06/10 12:05, , 1F
果然 -.- 這就是我跟你說他嘛煩得地方
06/10 12:05, 1F
文章代碼(AID): #18JTwvYx (java)
討論串 (同標題文章)
文章代碼(AID): #18JTwvYx (java)