// importing javax.swing package import javax.swing.*; // Creating a JFrame object JFrame f = new JFrame("Text Field Example"); // Creating a JTextField object JTextField tf = new JTextField(); // Creating a Document object Document doc = new PlainDocument(); // Setting the document of the text field tf.setDocument(doc); // Adding the text field to the frame f.add(tf); // Setting the size, layout, and visibility of the frame f.setSize(300, 300); f.setLayout(null); f.setVisible(true);
// importing javax.swing package import javax.swing.*; // Creating a JFrame object JFrame f = new JFrame("Text Field Example"); // Creating a JTextField object JTextField tf = new JTextField(); // Creating a DocumentFilter object DocumentFilter filter = new DocumentFilter() { public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (text.matches("\\d+")) { super.replace(fb, offset, length, text, attrs); } } }; // Setting the document filter of the document of the text field ((AbstractDocument) tf.getDocument()).setDocumentFilter(filter); // Adding the text field to the frame f.add(tf); // Setting the size, layout, and visibility of the frame f.setSize(300, 300); f.setLayout(null); f.setVisible(true);In this example, we create a JFrame object and a JTextField object. We then create a DocumentFilter object, which filters the content of the text field by only allowing numeric input. We set the document filter of the document of the text field using the setDocumentFilter method of the AbstractDocument class. Finally, we add the text field to the frame and set the size, layout, and visibility of the frame. The package library for the javax.swing classes is the Java Foundation Classes (JFC) library, which is part of the Java Standard Edition (Java SE) platform.