A JTextField can handle one line of plain text. Its constructors accept a combination of the following three values.
The document model is an instance of the PlainDocument
class.
The following table lists constructors of the JTextField class.
ID | Constructor/Description |
---|---|
1 | JTextField() Creates a JTextField with default values for initial text, number of columns, and document. |
2 | JTextField(Document document, String text, int columns) Creates a JTextField with the specified document as its model, text as its initial text, and columns as its number of columns. |
3 | JTextField(int columns) Creates a JTextField with the specified columns as its number of columns. |
4 | JTextField(String text) Creates a JTextField with the specified text as its initial text. |
5 | JTextField(String text, int columns) Creates a JTextField with the specified text as its initial text and columns as its number of columns. |
6 | |
7 |
To create an empty JTextField
JTextField emptyTextField = new JTextField();
To create a JTextField with an initial text of Hello
JTextField helloTextField = new JTextField("Hello");
To create a JTextField with the number of columns of 20
JTextField nameTextField = new JTextField(20);
By default, the text alignment is left-justified.
public void setHorizontalAlignment(int alignment) method takes an argument of
import java.awt.BorderLayout; import java.awt.event.KeyEvent; /* w w w . j ava2 s. co m*/ import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { public static void main(String args[]) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Name: "); label.setDisplayedMnemonic(KeyEvent.VK_N); JTextField textField = new JTextField(); textField.setHorizontalAlignment(JTextField.CENTER) ; label.setLabelFor(textField); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); frame.add(panel, BorderLayout.NORTH); frame.setSize(250, 150); frame.setVisible(true); } }
The following code shows how to mirror a JTextField by Sharing Its Model With Another JTextField.
import java.awt.Container; import java.awt.GridLayout; /*from w ww.jav a 2s . co m*/ import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.text.Document; public class Main extends JFrame { JLabel nameLabel = new JLabel("Name:"); JLabel mirroredNameLabel = new JLabel("Mirrored:"); JTextField name = new JTextField(20); JTextField mirroredName = new JTextField(20); public Main() { this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new GridLayout(2, 0)); Container contentPane = this.getContentPane(); contentPane.add(nameLabel); contentPane.add(name); contentPane.add(mirroredNameLabel); contentPane.add(mirroredName); Document nameModel = name.getDocument(); mirroredName.setDocument(nameModel); pack(); setVisible(true); } public static void main(String[] args) { Main frame = new Main(); } }
To create our own model for a JTextField, create a new class which either implements
the Document
interface or inherit from the PlainDocument
class.
The following code contains a LimitedCharDocument class, which inherits from the PlainDocument class.
import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; class LimitedCharDocument extends PlainDocument { private int limit = 10; public LimitedCharDocument() { } @Override public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { String newString = str; if (str != null) { int currentLength = this.getLength(); int newTextLength = str.length(); if (currentLength + newTextLength > limit) { newString = str.substring(0, limit - currentLength); } } super.insertString(offset, newString, a); } }
The insertString() of the model is called every time a text is inserted into the JTextField. This method gets the following three arguments:
int offset
is the position where the string is inserted in the JTextField.
String str
is the string that is inserted into the JTextField.
AttributeSet a
is associated with the inserted text.
We can use the LimitedCharDocument as follows:
Document tenCharDoc = new LimitedCharDocument(10); JTextField t1 = new JTextField(tenCharDoc, "your name", 10);
There is another way to set a document for a JTextField. We can create a new class inheriting from JTextField and override its createDefaultModel() method.
createDefaultModel() method is declared protected in the JTextField class and it returns a PlainDocument.
To customize JTextField we can return an instance of custom document class from this method.
The code for creating custom JTextField.
class TenCharTextField extends JTextField { @Override protected Document createDefaultModel() { return new LimitedCharDocument(10); } }
The following code shows how to add Action Listener to JTextField. The Action Listener is triggered when clicking the enter button.
import java.awt.event.ActionEvent; //from w w w. ja va2s .c o m import javax.swing.JFrame; import javax.swing.JTextField; public class Main { public static void main(String[] a) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField jTextField1 = new JTextField(); jTextField1.setText("jTextField1"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("action"); } }); frame.add(jTextField1); frame.setSize(300, 200); frame.setVisible(true); } }
The following code shows how to use InputVerifier to verify input during focus Traversal.
import java.awt.BorderLayout; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextField; public class Main { public static void main(String args[]) { JFrame frame = new JFrame("Verifier Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField textField1 = new JTextField(); JTextField textField2 = new JTextField(); InputVerifier verifier = new InputVerifier() { public boolean verify(JComponent comp) { boolean returnValue; JTextField textField = (JTextField) comp; try {//from w ww . j ava 2 s.c o m Integer.parseInt(textField.getText()); returnValue = true; } catch (NumberFormatException e) { returnValue = false; } return returnValue; } }; textField1.setInputVerifier(verifier); frame.add(textField1, BorderLayout.NORTH); frame.add(textField2, BorderLayout.CENTER); frame.setSize(300, 100); frame.setVisible(true); } }
To make sure that the end of the contents is visible, change the scrollOffset setting.
import java.awt.BorderLayout; import java.awt.event.KeyEvent; /* w ww . j av a 2s . c o m*/ import javax.swing.BoundedRangeModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { public static void main(String args[]) { JFrame frame = new JFrame("Label Focus Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Name: "); label.setDisplayedMnemonic(KeyEvent.VK_N); JTextField textField = new JTextField(); label.setLabelFor(textField); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); frame.add(panel, BorderLayout.NORTH); frame.setSize(250, 150); frame.setVisible(true); textField.setText("Loooooooooooooooooooooooooooooooooooooooooooooooooooooooong"); BoundedRangeModel model = textField.getHorizontalVisibility(); int extent = model.getExtent(); textField.setScrollOffset(extent); System.out.println("extent:"+extent); } }
The following code shows how to use the write() method to write the contents.
import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.io.FileWriter; import java.io.IOException; /*w w w . ja va2 s . c om*/ import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { public static void main(String args[]) { JFrame frame = new JFrame("Label Focus Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Name: "); label.setDisplayedMnemonic(KeyEvent.VK_N); JTextField textField = new JTextField(); label.setLabelFor(textField); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); frame.add(panel, BorderLayout.NORTH); frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH); frame.setSize(250, 150); frame.setVisible(true); textField.setText("your text"); String filename = "test.txt"; FileWriter writer = null; try { writer = new FileWriter(filename); textField.write(writer); } catch (IOException exception) { System.err.println("Save oops"); } finally { if (writer != null) { try { writer.close(); } catch (IOException exception) { System.err.println("Error closing writer"); exception.printStackTrace(); } } } } }
import java.awt.Container; /*from w w w . j a v a 2s. com*/ import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JTextField; public class DragDropText extends JFrame { public static void main(String[] args) { new DragDropText().setVisible(true); } public DragDropText() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField field1 = new JTextField("Life's a drag", 20); JTextField field2 = new JTextField("and then you drop", 20); field1.setDragEnabled(true); field2.setDragEnabled(true); Container content = getContentPane(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); content.add(field1); content.add(field2); pack(); } }
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // w ww. j a v a 2 s .co m import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; public class Main { public static void main(String args[]) { final JTextField textField = new JTextField(15); JButton buttonCut = new JButton("Cut"); JButton buttonPaste = new JButton("Paste"); JButton buttonCopy = new JButton("Copy"); JFrame jfrm = new JFrame("Cut, Copy, and Paste"); jfrm.setLayout(new FlowLayout()); jfrm.setSize(230, 150); jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); buttonCut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { textField.cut(); } }); buttonPaste.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { textField.paste(); } }); buttonCopy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { textField.copy(); } }); textField.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent ce) { System.out.println("All text: " + textField.getText()); if (textField.getSelectedText() != null) System.out.println("Selected text: " + textField.getSelectedText()); else System.out.println("Selected text: "); } }); jfrm.add(textField); jfrm.add(buttonCut); jfrm.add(buttonPaste); jfrm.add(buttonCopy); jfrm.setVisible(true); } }
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; //from w w w . j a v a 2s . co m import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class Main extends JFrame { public Main() throws HeadlessException { setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel usernameLabel = new JLabel("Username: "); JTextField usernameTextField = new JTextField(); usernameTextField.setPreferredSize(new Dimension(100, 20)); add(usernameLabel); add(usernameTextField); usernameTextField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { JTextField textField = (JTextField) e.getSource(); String text = textField.getText(); textField.setText(text.toUpperCase()); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } }); } public static void main(String[] args) { new Main().setVisible(true); } }
import javax.swing.JTextField; import javax.swing.SwingUtilities; /* w w w . j a v a2s.c o m*/ public class Main { public static void main(String[] argv) throws Exception { final JTextField textfield = new JTextField(10); SwingUtilities.invokeLater(new Runnable() { public void run() { textfield.requestFocus(); } }); } }
import java.awt.BorderLayout; /* ww w .j ava 2 s.c o m*/ import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; public class Main { public Main() { JButton button = new JButton("foo"); JTextField textField = new JTextField(10); Document document = textField.getDocument(); document.addDocumentListener(new JButtonStateController(button)); JFrame frame = new JFrame(); frame.add(button,BorderLayout.WEST); frame.add(textField,BorderLayout.CENTER); frame.setSize(300,300); frame.setVisible(true); } } class JButtonStateController implements DocumentListener { JButton button; JButtonStateController(JButton button) { this.button = button ; } public void changedUpdate(DocumentEvent e) { disableIfEmpty(e); } public void insertUpdate(DocumentEvent e) { disableIfEmpty(e); } public void removeUpdate(DocumentEvent e) { disableIfEmpty(e); } public void disableIfEmpty(DocumentEvent e) { button.setEnabled(e.getDocument().getLength() > 0); } }