JTextField Sample 2 : TextField « Swing JFC « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » Swing JFC » TextFieldScreenshots 
JTextField Sample 2
JTextField Sample 2
    
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

public class JTextFieldSample {
  public static void main(String args[]) {
    String title = (args.length == "TextField Listener Example"
        : args[0]);
    JFrame frame = new JFrame(title);
    Container content = frame.getContentPane();

    JPanel namePanel = new JPanel(new BorderLayout());
    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField nameTextField = new JTextField();
    nameLabel.setLabelFor(nameTextField);
    namePanel.add(nameLabel, BorderLayout.WEST);
    namePanel.add(nameTextField, BorderLayout.CENTER);
    content.add(namePanel, BorderLayout.NORTH);

    JPanel cityPanel = new JPanel(new BorderLayout());
    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setDisplayedMnemonic(KeyEvent.VK_C);
    JTextField cityTextField = new JTextField();
    cityLabel.setLabelFor(cityTextField);
    cityPanel.add(cityLabel, BorderLayout.WEST);
    cityPanel.add(cityTextField, BorderLayout.CENTER);
    content.add(cityPanel, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out
            .println("Command: " + actionEvent.getActionCommand());
      }
    };
    nameTextField.setActionCommand("Yo");
    nameTextField.addActionListener(actionListener);
    cityTextField.addActionListener(actionListener);

    KeyListener keyListener = new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {
        printIt("Pressed", keyEvent);
      }

      public void keyReleased(KeyEvent keyEvent) {
        printIt("Released", keyEvent);
      }

      public void keyTyped(KeyEvent keyEvent) {
        printIt("Typed", keyEvent);
      }

      private void printIt(String title, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println(title + " : " + keyText + " / "
            + keyEvent.getKeyChar());
      }
    };
    nameTextField.addKeyListener(keyListener);
    cityTextField.addKeyListener(keyListener);

    InputVerifier verifier = new InputVerifier() {
      public boolean verify(JComponent input) {
        final JTextComponent source = (JTextComponentinput;
        String text = source.getText();
        if ((text.length() != 0&& !(text.equals("Exit"))) {
          Runnable runnable = new Runnable() {
            public void run() {
              JOptionPane.showMessageDialog(source,
                  "Can't leave.""Error Dialog",
                  JOptionPane.ERROR_MESSAGE);
            }
          };
          SwingUtilities.invokeLater(runnable);
          return false;
        else {
          return true;
        }
      }
    };
    nameTextField.setInputVerifier(verifier);
    cityTextField.setInputVerifier(verifier);

    DocumentListener documentListener = new DocumentListener() {
      public void changedUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }

      public void insertUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }

      public void removeUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }

      private void printIt(DocumentEvent documentEvent) {
        DocumentEvent.EventType type = documentEvent.getType();
        String typeString = null;
        if (type.equals(DocumentEvent.EventType.CHANGE)) {
          typeString = "Change";
        else if (type.equals(DocumentEvent.EventType.INSERT)) {
          typeString = "Insert";
        else if (type.equals(DocumentEvent.EventType.REMOVE)) {
          typeString = "Remove";
        }
        System.out.print("Type  :   " + typeString + " / ");
        Document source = documentEvent.getDocument();
        int length = source.getLength();
        try {
          System.out
              .println("Contents: " + source.getText(0, length));
        catch (BadLocationException badLocationException) {
          System.out.println("Contents: Unknown");
        }
      }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    cityTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250150);
    frame.setVisible(true);
  }
}

           
         
    
    
    
  
Related examples in the same category
1.Make a Text Field two columns wide
2.Water mark text field
3.Auto complete TextField
4.Text fields and Java eventsText fields and Java events
5.JTextField Alignment SampleJTextField Alignment Sample
6.Create the textfieldCreate the textfield
7.FieldEdit - an Applet to validate data as it's being entered
8.Textfield only accepts numbersTextfield only accepts numbers
9.Overwritable TextFieldOverwritable TextField
10.Numeric TextFieldNumeric TextField
11.Passive TextField 1Passive TextField 1
12.Passive TextField 2Passive TextField 2
13.Text Accelerator ExampleText Accelerator Example
14.TextField Look Ahead ExampleTextField Look Ahead Example
15.Passive TextField 3Passive TextField 3
16.Non Wrapping(Wrap) TextPaneNon Wrapping(Wrap) TextPane
17.EditabilityExampleEditabilityExample
18.Bounded TextFieldBounded TextField
19.TextField ElementsTextField Elements
20.TextFieldViews 2TextFieldViews 2
21.TextField with ConstaintsTextField with Constaints
22.JTextField Verifier SampleJTextField Verifier Sample
23.A simple label for field form panelA simple label for field form panel
24.A hack to make a JTextField really 2 columns wideA hack to make a JTextField really 2 columns wide
25.Limit JTextField input to a maximum length
26.Make sure that my JTextField has the focus when a JFrame is created
27.Make the ENTER key act like the TAB key
28.Setting up a textfield and modifying its horizontal alignment at runtimeSetting up a textfield and modifying its horizontal alignment at runtime
29.Aligning the Text in a JTextField Component
30.Based on JTextField content, enable or disable a JButton
31.Cut, paste, and copy in a JTextField under program control.
32.Add key listener event handler to JTextField
33.Right justified JTextfield content
34.Set the focus on a particular JTextField
35.Associate JLabel component with a JTextField
36.Right justified JTextField contents
37.Validate a value on the lostFocus event
38.Modify horizontal alignment of text field at runtime
39.Make sure that my Text field has the focus when a JFrame is created
40.Firing Item Events
41.extends JTextField to create integer JTextField
42.JTextField Max Length
43.Demo for three types of text component: JTextField, JPasswordField, JTextArea
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.