Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I limit a TextField to no more than N characters, or to only allow numeric input?

0
10 Posted

How can I limit a TextField to no more than N characters, or to only allow numeric input?

0
10

• 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

0

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

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123