Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_java thread: JText Filed problem


Message #1 by misbah_ansari@y... on Wed, 5 Feb 2003 12:06:27
> Hello everyone,
> I am a vb programer and also keen to learn java.I have three questions if
> someone can answer i will be greatful.
> 1)how can we restrict the length of JTextbox (i.e.i want not more than 4
> characters in it)?
> 2)Is there a way that only numericvalue(whole number) can be entered (i.e.
> like the facility editmask control provides us  in vb)?
> 3) Last but not the least , how canwe exit function on our will (i.e. some
> condition gets true and i do not want the remaing part of the function
> execute like we have exit funtion  statement to exit funtion in vb)?
> Thanks in advance.

hello juga,

this will answer your problems.

import java.awt.Toolkit;
import javax.swing.text.*;

class Num extends PlainDocument {
protected int max = 0;
protected static Toolkit toolkit = Toolkit.getDefaultToolkit();
public Num(int max) {
 super();
 this.max = max;
}
public Num() {
 this(-1);
}
public int getMax() {
 return max;
}
public void insertString(int offset, String text, AttributeSet attr) throws
BadLocationException {
 int count = text.length();
 for (int pos=0;pos<count;pos++) {
  if (!(Character.isDigit(text.charAt(pos)))) {
   return;
  }
 }
 if ((max > 0) && ((getLength() + count) > max)) {
  return;
 }
 super.insertString(offset,text,attr);
}
}

class NumericText extends JTextField {
  public NumericText(String text,int column) {
   super(text,column);
  }
  protected Document createDefaultModel() {
   return new Num(getColumns());
  }
}

here's the implementation
-------------------------------

public class Frame1 extends JFrame {
  ...
  NumericText jTextField1 = new NumericText("",4);
  ...

or
------
  ...
  JTextField jTextField1 = new JTextField(new Num(5),"",5);
  ...









  Return to Index