Im trying to limit the number of characters that can be entered into my showInputDiaglog box but really don't know how to go about it. I've got the input box and output box working but need to add something to limit the amount of characters and display an error message if the amount is invalid.
Any help will be apretiated :)|||You cannot do this, because such validation is not the intended purposed of the function.
.|||Java Swing is all engineered for the MVC. With OptionPanes you have choices that let you pass custom thingy's into the Dialog. We look for the OptionPaneDialog with object as one of the attributes, we make and Array of Object[] and pass that in.
The choice here is to give in a String, and a JTextField. We modify the JTextField with its own Document model and override a single method. Here I chose insertString, IF we under the char limiit. Otherwise ... don't do nothing.
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class InputDialog_limitTextfield {
public static void main(String[] args) {
JTextField tf = new JTextField(new CharLimitDocument(5), "", 5);
Object[] msg = {
"Enter zip code: (5 characters)", tf
};
int result = JOptionPane.showConfirmDialog(null,
msg, "Enter zip code...",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
String input = tf.getText();
if (!input.equals("")) {
// data entered
} else {
// nothing entered
}
} else {
// cancelled
}
}
static class CharLimitDocument extends PlainDocument {
int maxLength;
public CharLimitDocument(int fieldWidth) {
super();
maxLength = fieldWidth;
}
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (getLength() + str.length() %26gt; maxLength) {
return;
}
super.insertString( offset, str, attr);
}
}
}|||Use a slice on the answer.
x[0:9]
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment