Re: [J2SE] 有關 javax.swing.JTextField
※ 引述《csihcs (非天夜翔)》之銘言:
: ※ 引述《csihcs (非天夜翔)》之銘言:
: 聽了 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
這段我以前寫過類似的CODE,所以還有一點點微薄的印象。
因為你修改->有異動又跑回來這個事件->可能又會回來這個事件,
所以可能會有遞迴現象,所以這個地方他直接禁止你改。
我記得以前好像是用一個第二方的thread來做跨thread的修改,
那時候沒想太多,不過顯然不是很好的解決方案。
剛剛爬了一下 Tutorials相關部份( http://0rz.tw/7e4ep )
在Filter的地方有提到 JTextPane可以用 Filter設定長度,
如果你可以接受把JTextField改成JTextPane,
底下有一個簡單的sample可以試著run起來看看。
http://tony1223.no-ip.org:1986/JSPWiki/Wiki.jsp?page=Java_gui_jtp_maxlength
--
▄▅▆▇███▇▆▅▄▃ ╰┼╯─╮ ╮
◥███████████◣ ╰┼╯=│=│
◥██████───────◣ *. ╯ ╯ ╯ の 物 語 .*
◥███████──────◣ ~ ◢◣ ◢◣
◥██████───────◤ ◥◤* 空白的世界.翼 *◥◤
◥██▁▂▃▄▅▆▇███▆▅▄▃▂▂~telnet://tony1223.no-ip.info
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.134.27.68
討論串 (同標題文章)