Valhalla Legends Forums Archive | Java Programming | Is it possible to set a fixed input size for a text field?

AuthorMessageTime
bethra
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.
September 25, 2005, 10:50 PM
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:

[code]
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;
}
[/code]

Or if you are hand coding it use:
[code]
jTextField = new JTextField();
jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
        if(getJTextField().getText().length() > 1) {
    //...etc
}
}
});
[/code]

or create a new class to handle the validation seperately and add the key listener that way
September 26, 2005, 1:30 AM

Search