To change JTextField
text to upper case can be easily done by adding a DocumentFilter
to the JTextField
component using the setDocumentFilter()
method. The DocumentFilter
allow us to filter action for changes in the document such as insert, replace and remove.
The code snippet below show us how to do it.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
public class DocumentFilterExample extends JFrame {
public DocumentFilterExample() throws HeadlessException {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true));
}
protected void initComponents() {
setSize(500, 500);
setTitle("DocumentFilter Example");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
JTextField firstName = new JTextField();
firstName.setPreferredSize(new Dimension(150, 20));
JTextField lastName = new JTextField();
lastName.setPreferredSize(new Dimension(150, 20));
DocumentFilter filter = new UppercaseDocumentFilter();
AbstractDocument firstNameDoc = (AbstractDocument) firstName.getDocument();
firstNameDoc.setDocumentFilter(filter);
AbstractDocument lastNameDoc = (AbstractDocument) lastName.getDocument();
lastNameDoc.setDocumentFilter(filter);
getContentPane().add(new JLabel("First Name: "));
getContentPane().add(firstName);
getContentPane().add(new JLabel("Last Name: "));
getContentPane().add(lastName);
}
static class UppercaseDocumentFilter extends DocumentFilter {
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr)
throws BadLocationException {
fb.insertString(offset, text.toUpperCase(), attr);
}
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024