Friday, September 2, 2011

Java JTextField class

Java Swing Tutorial Explaining the JTextField Component. JTextField allows editing/displaying of a single line of text. New features include the ability to justify the text left, right, or center, and to set the text’s font. When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the listener processes the event and can use the data in the text field at the time of the event in the program. JTextField is an input area where the user can type in characters. If you want to let the user enter multiple lines of text, you cannot use Jtextfield’s unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.

JTextField Source Code

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

public class JTextFieldDemo extends JFrame {

	//Class Declarations
	JTextField jtfText1, jtfUneditableText;
	String disp = "";
	TextHandler handler = null;
	//Constructor
	public JTextFieldDemo() {
		super("TextField Test Demo");
		Container container = getContentPane();
		container.setLayout(new FlowLayout());
		jtfText1 = new JTextField(10);
                jtfUneditableText = new JTextField("Uneditable text field", 20);
		jtfUneditableText.setEditable(false);
		container.add(jtfText1);
		container.add(jtfUneditableText);
		handler = new TextHandler();
		jtfText1.addActionListener(handler);
		jtfUneditableText.addActionListener(handler);
		setSize(325, 100);
		setVisible(true);
	}
	//Inner Class TextHandler
	private class TextHandler implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == jtfText1) {
				disp = "text1 : " + e.getActionCommand();
			} else if (e.getSource() == jtfUneditableText) {
				disp = "text3 : " + e.getActionCommand();
			}
			JOptionPane.showMessageDialog(null, disp);
		}
	}
	//Main Program that starts Execution
	public static void main(String args[]) {
		JTextFieldDemo test = new JTextFieldDemo();
		test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}
Output


 

No comments:

Post a Comment