• Welcome to Valhalla Legends Archive.
 

Is it possible to set a fixed input size for a text field?

Started by Sorc.Polgara, September 25, 2005, 05:50 PM

Previous topic - Next topic

Sorc.Polgara

I want to have my text field only hold one character.  Is there a way to do this?  I mean, I can set the size of the text field but it doesn't restrain how many characters you can enter in there.

Help please.

gameschild

As far as i know you can't place those kind of constraints on it, but you can check it when a key is pressed.I f you are using Visual Editor under Eclipse use:


private JTextField getJTextField() {
if (jTextField == null) {
jTextField = new JTextField();
jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if(getJTextField().getText().length() > 1) {
//...etc
}
}
});
}
return jTextField;
}


Or if you are hand coding it use:

jTextField = new JTextField();
jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
        if(getJTextField().getText().length() > 1) {
    //...etc
}
}
});


or create a new class to handle the validation seperately and add the key listener that way