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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JTextField problem 1

Status
Not open for further replies.

DigitalOx

Programmer
Sep 29, 1998
41
0
0
US
Hello all,<br>
<br>
I'm using to JTextField to get some input, and noticed that even though I specify the width to be certain number of columns, the user can keep typing to his/her heart's content. I suppose I could check the string length using keylistener and such, but this seems like the hard way. I can't find the function to limit the length, is there one?<br>
<br>
DigitalOx
 
Hi!<br>
<br>
Unfortunately the columns only used when the swing estimate the preferred size. I give you a little code. It is an another way, maybe simply than listeners, I do not know.<br>
**********<br>
import java.awt.event.*;<br>
import javax.swing.*;<br>
import javax.swing.text.*;<br>
<br>
public class LimitedText {<br>
static JFrame frame;<br>
<br>
public static void main(String[] args) {<br>
frame=new JFrame("Limited Text-Length JTextField");<br>
frame.addWindowListener(new WindowAdapter() {<br>
public void windowClosing(WindowEvent e) {System.exit(0);}<br>
});<br>
frame.getContentPane().add("North", new LimitedField(5));<br>
frame.pack();<br>
frame.setSize(320, 200);<br>
frame.setVisible(true);<br>
}<br>
}<br>
<br>
class LimitedField extends JTextField {<br>
int maxLength;<br>
<br>
LimitedField(int cols) {<br>
super(cols);<br>
((LimitedDocument) getDocument()).setMaxLength(cols);<br>
}<br>
<br>
protected Document createDefaultModel() {<br>
return new LimitedDocument();<br>
}<br>
<br>
static class LimitedDocument extends PlainDocument {<br>
int maxLength;<br>
<br>
public void setMaxLength(int maxLength) {<br>
this.maxLength=maxLength;<br>
}<br>
<br>
public void insertString(int offs, String str, AttributeSet a) <br>
throws BadLocationException {<br>
if (str==null) { return; }<br>
else {<br>
if (offs&gt;maxLength-1) {<br>
java.awt.Toolkit.getDefaultToolkit().beep();<br>
return;<br>
}<br>
else {<br>
super.insertString(offs, str.substring(0, Math.min(str.length(),<br>
maxLength-offs)), a);<br>
}<br>
}<br>
}<br>
}<br>
}<br>
<br>
Good luck. Bye, Otto.<br>

 
Easy enough.<br>
Thanks Otto<br>
<br>
DigitalOx
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top