JTextField
JTextField Source Code
Sept 18, 2006 by Hemanth
// A program to demonstrate the use of JTextFields's //Import Statements 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); } }// End of class TextFieldTest
Output
Download jTextField Source Code
Another Example: JTextField Source Code
Sept 23, 2006 by Hemanth
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JTextFieldDemo2 extends JFrame implements ActionListener { JTextField jtfInput; JTextArea jtAreaOutput; String newline = "\n"; public JTextFieldDemo2() { createGui(); } public void createGui() { jtfInput = new JTextField(20); jtfInput.addActionListener(this); jtAreaOutput = new JTextArea(5, 20); jtAreaOutput.setEditable(false); JScrollPane scrollPane = new JScrollPane(jtAreaOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); GridBagLayout gridBag = new GridBagLayout(); Container contentPane = getContentPane(); contentPane.setLayout(gridBag); GridBagConstraints gridCons1 = new GridBagConstraints(); gridCons1.gridwidth = GridBagConstraints.REMAINDER; gridCons1.fill = GridBagConstraints.HORIZONTAL; contentPane.add(jtfInput, gridCons1); GridBagConstraints gridCons2 = new GridBagConstraints(); gridCons2.weightx = 1.0; gridCons2.weighty = 1.0; contentPane.add(scrollPane, gridCons2); } public void actionPerformed(ActionEvent evt) { String text = jtfInput.getText(); jtAreaOutput.append(text + newline); jtfInput.selectAll(); } public static void main(String[] args) { JTextFieldDemo2 jtfTfDemo = new JTextFieldDemo2(); jtfTfDemo.pack(); jtfTfDemo.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); jtfTfDemo.setVisible(true); } }
Output
Download jTextField Source Code