Robert Stone
Posts: 2
Nickname: ph4nt0m
Registered: Apr, 2005
|
|
Re: How can I limit the number of characters entered into a JTextField?
|
Posted: Apr 24, 2005 5:54 PM
|
|
I got the answer. Thanks anyway.
Just incase anyone is curious this is the answer
The best way to do this is to subclass the JTextField class and then add a KeyListener to determine if you reached the limit that will be passed in the constructor of the subclassed class.
import java.awt.event.*; import java.awt.*; import com.sun.java.swing.*;
public class SetLimit {
public static void main(String args[]) { new SetLimitFrame(); } }
class SetLimitFrame extends JFrame { MyTextField mtf = new MyTextField(20,5);
SetLimitFrame() { super();
/* Components should be added to the container's content pane */ Container cp = getContentPane();
/* Add the window listener */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { dispose(); System.exit(0);}});
cp.add(BorderLayout.NORTH,mtf);
/* Size the frame */ setSize(200,200);
/* Center the frame */ Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle frameDim = getBounds(); setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
/* Show the frame */ setVisible(true); } }
class MyTextField extends JTextField { int limit;
MyTextField(int show,int limit) { super(show);
this.limit = limit;
addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent evt) { if (getText().length() >= MyTextField.this.limit) evt.consume();}}); } }
|
|