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.

Force JTextField to convert input to upper case with PlainDocument in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer