Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Fixed length JTextBox

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
This should be easy i guess... I need to create a JTextBox that would only allow 2 characters to be inserted. I thought that by doing new JTextBox(2) would solve the problem, but it doesn't... I can't add a keylistener to it and every time the user presses a key I would check the length of the textbox.getText string, but there should be a immediate way right?
 
Nope, setColumns only affects the 'visible' width, not how many characters the box can contain. This is (essentially) unbounded. You will have to do something similar to what you are already planning.
 
I must admit, I haven't heard of a JTextBox, but what you need can be done in exactly the same way with a JTextField.

e.g

JTextField myfield = new JTextField(2);
 
pipk: Sorry I mistyped it, I was speaking of a JTextField... so your solution also wouldn't work.

meadandale: That's what I suspected :( but I've been looking into the online documentation and I think I can do it with a JTextArea by setting a DefaultStyledDocument to it... and that would probably be sufficient for what I want. I will try to do it this way though since it seems there's no straight forward method to do so...

Thank you for the replies both.
 
no, meadandale is correct, I think I must have been typing mine when he submitted his answer. But I have checked it on my own apps at home and can confirm what he said.

However, I do have a JTextArea containing a keylistener, it just counts the number of times a key is pressed when the focus is on the area (taking into account the usual keycodes to ignore) and checks to see if the count has exceeded a specific number.
 
import java.awt.event.*;
import javax.swing.JTextField;

public class Ad implements KeyListener {
private int length;
public Ad(int length) {
this.length = length;
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
JTextField t = (JTextField) e.getSource();
int l = t.getText().length();
if (!(l < length)) {
e.consume();
return;
}
}
}

some other class...
JTextField myField = new JTextField(15);
myField.addKeyListener(new Ad(2));
::)
 
pipk: That was more or less what I was trying to do, but I would use a DefaultStyledDocument for it. But in fact pallavgrigo's code seems to work for what I want so I'll probably end up using something like that :)

Thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top