Jtextfield in swing Development

Source: Internet
Author: User

Jtextfield inherits the jtextcomponent class, so it can also use many useful methods in the jtextcomponent abstract class, such as copy (), paste (), settext (), and iseditable. We can use jtextfield in many places. jtextfield is a single row input component.

Jtextfield has a method to create a string, which is used as a command string for the triggered operation event. Java. AWT. textfield uses the field text as a command string for actionevent. If the command string set using the setactioncommand method is not null, jtextfield uses this string to maintain compatibility with Java. AWT. textfield. Otherwise, field text is used for compatibility.

The setechochar and getechochar methods are not directly provided to avoid unexpected disclosure of password characters in the new implementations of pluggable appearances. To provide password-like services, a separate class jpasswordfield extends jtextfield to provide this service independently through the pluggable appearance.

Constructor:
Jtextfield ()
Construct a new textfield.
Jtextfield (document DOC, string text, int columns)
Construct a new jtextfield that uses the given text storage model and the given number of columns.
Jtextfield (INT columns)
Creates a new blank textfield with the specified number of columns.
Jtextfield (string text)
Creates a new textfield initialized with the specified text.
Jtextfield (string text, int columns)
Constructs a new textfield initialized with the specified text and column.

Common Methods:
Addactionlistener (actionlistener L)
Add the specified operation listener to receive operation events from this text field.
Getcolumns ()
Returns the number of columns in the textfield.
Getcolumnwidth ()
Returns the column width.
Setactioncommand (string command)
Set the command string used to operate the event.
Setdocument (document DOC)
Associate the editor with a text document.
Setfont (font F)
Set the current font.
Sethorizontalalignment (INT alignment)
Sets the horizontal alignment of text.
Getdocument ()
Obtain the model associated with the editor.
Gettext ()
Returns the text contained in textcomponent.
Iseditable ()
Returns a Boolean that indicates whether the textcomponent can be edited.
Setdragenabled (Boolean B)
Set the dragenabled attribute. This attribute must be set to true to enable automatic drag processing for this component (the first part of the drag-and-drop operation ).
Seteditable (Boolean B)
Sets the specified Boolean variable to indicate whether the textcomponent should be editable.
Settext (string T)
Set the textcomponent text to the specified text.

Example 1: Shared Data Model

import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.text.Document; public class ShareModel {   public static void main(String args[]) {     JFrame frame = new JFrame("Sharing Sample");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     JTextField textarea1 = new JTextField();     Document document = textarea1.getDocument();     JTextArea textarea2 = new JTextArea(document);     JTextArea textarea3 = new JTextArea(document);     frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));     frame.add(new JScrollPane(textarea1));     frame.add(new JScrollPane(textarea2));     frame.add(new JScrollPane(textarea3));     frame.setSize(300, 400);     frame.setVisible(true);   } } 

Example 2: verification text box. If the first text box is a number, the second text box cannot be entered.

import java.awt.BorderLayout; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextField; public class VerifierSample {   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 {           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);   } } 

Example 3: add the text input box to the scroll bar panel.

import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoundedRangeModel; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JTextField; public class TextSlider {   public static void main(String args[]) {     JFrame frame = new JFrame("Text Slider");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     final JTextField textField = new JTextField();     JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);     JPanel panel = new JPanel();     panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));     BoundedRangeModel brm = textField.getHorizontalVisibility();     scrollBar.setModel(brm);     panel.add(textField);     panel.add(scrollBar);     final TextSlider ts = new TextSlider();     textField.addActionListener(new ActionListener() {       public void actionPerformed(ActionEvent e) {         System.out.println("Text: " + textField.getText());       }     });     frame.add(panel, BorderLayout.NORTH);     frame.setSize(300, 100);     frame.setVisible(true);   } } 

Example 4: during development, you can only enter the format you want to control in the text box. For example, you can only enter numbers, letters, and other similar requirements. There are two implementation methods for this requirement, one is to determine whether the input content meets the requirements when the user submits the request, and the other is to determine the content while the user inputs. the following example is the second method. by extending the model and changing the default model provided, you can easily create custom fields.

You can only enter numbers in the text box.

Import Java. AWT. container; import Java. AWT. graphics; import Java. AWT. event. windowadapter; import Java. AWT. event. using wevent; import javax. swing. jframe; import javax. swing. jlabel; import javax. swing. jpanel; import javax. swing. jtextfield; import javax. swing. event. documentevent; import javax. swing. event. documentlistener; import javax. swing. text. attributeset; import javax. swing. text. badlocationexception; import javax. swing. text. document; import javax. swing. text. plaindocument; public class validationtestframe extends jframe implements documentlistener {jlabel label = new jlabel ("I only accept numbers"); Private inttextfield intfiled; Public validationtestframe () {settitle ("validationtest "); setsize (300,200); addwindowlistener (New windowadapter () {public void windowclosing (LOGIN wevent e) {system. exit (0) ;}}); Container contentpane = getcontentpane (); jpanel P = new jpanel (); intfiled = new inttextfield (12, 3); p. add (intfiled); // added the documentlistener event intfiled. getdocument (). adddocumentlistener (this); contentpane. add (P, "South"); contentpane. add (label, "center");} public void insertupdate (documentevent e) {setlabel ();} public void removeupdate (documentevent e) {setlabel ();} public void changedupdate (documentevent e) {} public void setlabel () {If (intfiled. isvalid () {int value = intfiled. getvalue (); label. settext (integer. tostring (value) ;}} public static void main (string [] ARGs) {jframe frame = new validationtestframe (); frame. show () ;}} class inttextfield extends jtextfield {public inttextfield (INT defval, int size) {super ("" + defval, size);} protected document createdefadefamodel () {return New inttextdocument ();} public Boolean isvalid () {try {integer. parseint (gettext (); Return true;} catch (numberformatexception e) {return false;} public int getvalue () {try {return integer. parseint (gettext ();} catch (numberformatexception e) {return 0 ;}} class inttextdocument extends plaindocument {// public void insertstring (INT offs, string STR, attributeset A) throws badlocationexception {If (STR = NULL) return; string oldstring = gettext (0, getlength (); string newstring = oldstring. substring (0, offs) + STR + oldstring. substring (offs); try {integer. parseint (newstring + "0"); // determine the super. insertstring (offs, STR, a);} catch (numberformatexception e ){}}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.