Force JTextField to convert input to upper case with PlainDocument in Java
Description
The following code shows how to force JTextFiled to convert input to upper case with PlainDocument.
Example
import java.awt.FlowLayout;
// ww w . j av a 2s .co m
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class Main {
public static void main(String[] argv) {
JTextField tf = new JTextField(20);
UpperCaseDocument ucd = new UpperCaseDocument();
tf.setDocument(ucd);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(tf);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class UpperCaseDocument extends PlainDocument {
private boolean upperCase = true;
public void setUpperCase(boolean flag) {
upperCase = flag;
}
public void insertString(int offset, String str, AttributeSet attSet)
throws BadLocationException {
if (upperCase)
str = str.toUpperCase();
super.insertString(offset, str, attSet);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »