Chapter: Java The Complete Reference - Introducing GUI Programming with Swing - Exploring Swing

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

JTextField - Swing

JTextField is the simplest Swing text component. It is also probably its most widely used text component.

JTextField

JTextField is the simplest Swing text component. It is also probably its most widely used text component. JTextField allows you to edit one line of text. It is derived from JTextComponent, which provides the basic functionality common to Swing text components. JTextField uses the Document interface for its model. Three of JTextField’s constructors are shown here:

 

JTextField(int cols) JTextField(String str, int cols) JTextField(String str)

 

Here, str is the string to be initially presented, and cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string.

 

JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the user presses enter. A CaretEvent is fired each time the caret (i.e., the cursor) changes position. (CaretEvent is packaged in javax.swing.event.) Other events are also possible. In many cases, your program will not need to handle these events. Instead, you will simply obtain the string currently in the text field when it is needed. To obtain the text currently in the text field, call getText( ).

 

The following example illustrates JTextField. It creates a JTextField and adds it to the content pane. When the user presses enter, an action event is generated. This is handled by displaying the text in the status window.

 

// Demonstrate JTextField.

import java.awt.*;

 

import java.awt.event.*; import javax.swing.*; /*

 

<applet code="JTextFieldDemo" width=300 height=50> </applet>

 

*/

 

public class JTextFieldDemo extends JApplet { JTextField jtf;

 

public void init() { try {

 

SwingUtilities.invokeAndWait( new Runnable() {

 

public void run() { makeGUI();

 

}

 

}

 

);

 

} catch (Exception exc) {

 

System.out.println("Can't create because of " + exc);

 

}

 

}

 

private void makeGUI() {

 

     //Change to flow layout.

     setLayout(new FlowLayout());

 

     //Add text field to content pane.

 

     jtf = new JTextField(15); add(jtf);

 

jtf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) {

 

     //Show text when user presses ENTER.

     showStatus(jtf.getText());

 

}

 

});

Output from the text field example is shown here:



 
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.