How can I limit a TextField to no more than N characters, or to only allow numeric input?
• A. The approach is to look at keystrokes as they happen, and disallow input that does not meet your criteria. A neat variation is to extend the basic AWT component, and in your subclass also include the handler that will look at the keystrokes. This bundles everything neatly in one place. The code may look like: import java.awt.*; import java.awt.event.*; public class XCTextField extends java.awt.TextField implements java.awt.event.TextListener { public XCTextField(int columns) { super(columns); enableEvents(AWTEvent.FOCUS_EVENT_MASK); addTextListener(this); } // other constructors may be useful, too public void textValueChanged(java.awt.event.TextEvent event) { int col = this.getColumns(); int len = getText().length(); // int caret = getCaretPosition(); if (col > 0 && len > col) { // or if the char just entered is not numeric etc. String s = this.getText(); Toolkit.getDefaultToolkit().beep(); this.setText(s.substring(0,col)); this.setCaretPosition(col-1); // caret at end } } public
Ans : The approach is to look at keystrokes as they happen, and disallow input that does not meet your criteria. A neat variation is to extend the basic AWT component, and in your subclass also include the handler that will look at the keystrokes. This bundles everything neatly in one place. The code may look like: import java.awt.*; import java.awt.event.*; public class XCTextField extends java.awt.TextField implements java.awt.event.TextListener { public XCTextField(int columns) { super(columns); enableEvents(AWTEvent.FOCUS_EVENT_MASK); addTextListener(this); } // other constructors may be useful, too public void textValueChanged(java.awt.event.TextEvent event) { int col = this.getColumns(); int len = getText().length(); // int caret = getCaretPosition(); if (col > 0 && len > col) { // or if the char just entered is not numeric etc. String s = this.getText(); Toolkit.getDefaultToolkit().beep(); this.setText(s.substring(0,col)); this.setCaretPosition(col-1); // caret at end } } public