introduce
JTextField is a lightweight component that allows editing of single-line text.
JTextField has a method of creating a string that is used as a command string for the triggered operation event. Java.awt.TextField uses field text as a command string for ActionEvent. If the command string set through the setActionCommand method is not null, JTextField will use this string to maintain compatibility with java.awt.TextField, otherwise field text will be used to maintain compatibility.
The setEchoChar and getEchoChar methods are not provided directly to avoid accidental disclosure of password characters by new implementations with insertible appearance. To provide password-like services, a separate class JPasswordField extends JTextField to provide this service independently through an insertible appearance.
The horizontal alignment of JTextField can be set to left alignment, front alignment, center alignment, right alignment or tail alignment. Right alignment/tail alignment is used when the required field text size is smaller than the size assigned to it. This is determined by the setHorizontal Alignment and getHorizontal Alignment methods. Front-end alignment by default.
How a text field uses VK_ENTER events depends on whether the text field has any action listeners. If you have an action listener, VK_ENTER causes the listener to get an ActionEvent and use the VK_ENTER event. This is compatible with the way AWT text fields handle VK_ENTER events. If the text field does not operate on the listener, the VK_ENTER event is not used from version 1.3. Instead, it handles the binding of ancestor components, which will enable the default button feature of JFC/Swing.
Swing is not thread-safe
Constructor
JTextField() Constructs a New TextField
JTextField(Document doc, String text, int columns) constructs a new JTextField, which uses a given text storage model and a given number of columns.
JTextField(int columns) constructs a new empty TextField with a specified number of columns.
JTextField(String text) constructs a new TextField initialized with the specified text.
JTextField(String text, int columns) constructs a new TextField initialized with specified text and columns.
Common Functions
Get / set Horizontal Alignment (int alignment) sets / gets horizontal alignment of text. The horizontal alignment is JTextField.LEFT
JTextField.CENTER
JTextField.RIGHT
JTextField.LEADING
(the default)JTextField.TRAILING
setFont(Font font) Setting Font
SetScrollOffset (int scroll Offset) gets the scroll offset in pixels.
setDocument(Document doc) associates the editor with a text document, which means associating the text box with a text document. This will keep the content consistent, and if one changes, the other will change.
setInputVerifier(verifier) sets the validation method, and if the text fails to validate, it cannot focus on the next component, and it will focus on the text box all the time.
Whether setDragEnabled(boolean x) can drag and drop text in the text box, or true, means whether it can drag and drop text when it is selected.
Additional ActionListener (ActionListener Action) adds a listening mechanism, which triggers input text by pressing Enter, the same as the button listening mechanism.
Writer (InfileWriter writer) enters the contents of the text box into the file
Add KeyListener (KeyListener event) adds keyboard monitoring, triggering the keyboard when entering content in the text box. There are press, release, and type actions. For more information, see Official Documents
A simple example
import javax.swing.*; import java.awt.*; class text extends JFrame { private JTextField textField1; private JTextField textField2; public static void main(String args[]) { text my = new text(); my.setVisible(true); } public text() { //this.setBounds(100,100,300,200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new GridLayout(2, 1)); textField1 = new JTextField(10); textField2 = new JTextField(); panel.add(textField1); panel.add(textField2); this.getContentPane().add(panel, BorderLayout.CENTER); this.pack(); InputVerifier verifier = new InputVerifier() { //Adding validation methods @Override public boolean verify(JComponent input) { //overloaded function boolean value; textField1 = (JTextField) input; //Force the input component into a single-line text box of JTextField type return textField1.getText().equals("pass"); //pass when judging whether or not the input is entered, if not, the error will be validated } }; textField1.setInputVerifier(verifier); //Setting up authentication mode textField1.setHorizontalAlignment(JTextField.CENTER); //Setting Horizontal Alignment Font font = new Font("Regular script", Font.BOLD + Font.ITALIC, 20); textField1.setFont(font); //Setting fonts textField1.setDragEnabled(true); //Setting it in a single line text box can drag and drop text, but if it is false, it can't drag and drop text. } }
Associated Text Documents
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(); //Get the text document of the text box and associate it with the second text box mirroredName.setDocument(nameModel); //The contents of the two text boxes are interrelated, so that only one text needs to be entered and displayed in another text box. pack(); setVisible(true); } public static void main(String[] args) { Main frame = new Main(); } }
Explanation: Here we associate two text boxes, so that we can input one text box and update the content at the same time.
Action Listener
Enter text and press Enter to trigger
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"); //Adding monitoring mechanism 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); } }
Verify text content
Use InputVerifier ) Verification
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() { //Create a validation public boolean verify(JComponent comp) { boolean returnValue; JTextField textField = (JTextField) comp; //Force conversion, converting comp of control type to JTextFiled type try { Integer.parseInt(textField.getText()); //Converting input to int type triggers a //NumberFormateException error if the input string is not decimal returnValue = true; } catch (NumberFormatException e) { returnValue = false; } return returnValue; //If false is returned, the pointer will always be focused in this text box and cannot be moved to other components. } }; textField1.setInputVerifier(verifier); frame.add(textField1, BorderLayout.NORTH); frame.add(textField2, BorderLayout.CENTER); frame.setSize(300, 100); frame.setVisible(true); } }
Note: If you return false, the pointer will always be focused in this text box and cannot be moved to other components.
Save the contents of the text box to a file
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; class Main extends JFrame { private JTextField textField; private FileWriter writer; public static void main(String args[]) { Main my = new Main(); my.setVisible(true); } public Main() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); JButton button = new JButton("Function"); JLabel label = new JLabel("name"); textField = new JTextField(); panel.add(label, BorderLayout.WEST); panel.add(textField, BorderLayout.CENTER); String filename = "text.txt"; button.addActionListener(new ActionListener() { //Add a button trigger, where just click anniu to enter the contents of the text box into the file @Override public void actionPerformed(ActionEvent e) { try { writer = new FileWriter(filename, false); //Create an object to write to a file, where false means that it is not added at the end of the file textField.write(writer); //Write input from a single line of text to a file writer.close(); } catch (IOException e1) { e1.printStackTrace(); System.out.println("false"); } } }); panel.add(button, BorderLayout.SOUTH); this.getContentPane().add(panel, BorderLayout.CENTER); this.pack(); } }
Note: FileWriter class is used here to write content to a file. See my last article for details. Article
Copy, paste, and cut text
The time copy(), paste(), cut() functions used here
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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); } }
Explanation: Three buttons are used to monitor the operation. Just press the corresponding button to trigger the mechanism.
Adding keyboard monitoring mechanism
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; 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() { //Creating mechanisms public void keyReleased(KeyEvent e) { //Overload function, release key trigger JTextField textField = (JTextField) e.getSource(); //Get the component object that originally occurred event, which is both a text box object String text = textField.getText(); textField.setText(text.toUpperCase()); //Convert all lowercase letters to uppercase letters } public void keyTyped(KeyEvent e) { //Triggered when typing } public void keyPressed(KeyEvent e) { //Functions triggered when releasing keys } }); } public static void main(String[] args) { new Main().setVisible(true); } }