Java/Swing JFC/TextField

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Содержание

Add key listener event handler to JTextField

    
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(200, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel usernameLabel = new JLabel("Username: ");
    JTextField usernameTextField = new JTextField();
    usernameTextField.setPreferredSize(new Dimension(100, 20));
    add(usernameLabel);
    add(usernameTextField);
    usernameTextField.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        textField.setText(text.toUpperCase());
      }
      public void keyTyped(KeyEvent e) {
      }
      public void keyPressed(KeyEvent e) {
      }
    });
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





A hack to make a JTextField really 2 columns wide

   
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class WidthHack {
  public static void main(String[] args) {
    JTextField tf = new JTextField("mm");
    tf.setPreferredSize(tf.getPreferredSize());
    tf.setText("");
    JPanel pHacked = new JPanel();
    pHacked.setBorder(new javax.swing.border.TitledBorder("hacked 2 columns"));
    pHacked.add(tf);
    JPanel pStock = new JPanel();
    pStock.setBorder(new javax.swing.border.TitledBorder("stock 2 columns"));
    pStock.add(new JTextField(2));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new java.awt.GridLayout(0, 1));
    frame.getContentPane().add(pHacked);
    frame.getContentPane().add(pStock);
    frame.setSize(150, 150);
    frame.setVisible(true);
    tf.requestFocus();
  }
}





Aligning the Text in a JTextField Component

    
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) {
    JTextField textfield = new JTextField("Initial Text");
    // Left-justify the text
    textfield.setHorizontalAlignment(JTextField.LEFT);
    // Center the text
    textfield.setHorizontalAlignment(JTextField.CENTER);
    // Right-justify the text
    textfield.setHorizontalAlignment(JTextField.RIGHT);
  }
}





A simple label for field form panel

   
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TextForm extends JPanel {
  private JTextField[] fields;
  // Create a form with the specified labels, tooltips, and sizes.
  public TextForm(String[] labels, char[] mnemonics, int[] widths, String[] tips) {
    super(new BorderLayout());
    JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
    JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));
    add(labelPanel, BorderLayout.WEST);
    add(fieldPanel, BorderLayout.CENTER);
    fields = new JTextField[labels.length];
    for (int i = 0; i < labels.length; i += 1) {
      fields[i] = new JTextField();
      if (i < tips.length)
        fields[i].setToolTipText(tips[i]);
      if (i < widths.length)
        fields[i].setColumns(widths[i]);
      JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
      lab.setLabelFor(fields[i]);
      if (i < mnemonics.length)
        lab.setDisplayedMnemonic(mnemonics[i]);
      labelPanel.add(lab);
      JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
      p.add(fields[i]);
      fieldPanel.add(p);
    }
  }
  public String getText(int i) {
    return (fields[i].getText());
  }
  public static void main(String[] args) {
    String[] labels = { "First Name", "Middle Initial", "Last Name", "Age" };
    char[] mnemonics = { "F", "M", "L", "A" };
    int[] widths = { 15, 1, 15, 3 };
    String[] descs = { "First Name", "Middle Initial", "Last Name", "Age" };
    final TextForm form = new TextForm(labels, mnemonics, widths, descs);
    JButton submit = new JButton("Submit Form");
    submit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println(form.getText(0) + " " + form.getText(1) + ". " + form.getText(2)
            + ", age " + form.getText(3));
      }
    });
    JFrame f = new JFrame("Text Form Example");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(form, BorderLayout.NORTH);
    JPanel p = new JPanel();
    p.add(submit);
    f.getContentPane().add(p, BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
  }
}





Associate JLabel component with a JTextField

    
 
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(400, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel usernameLabel = new JLabel("Username: ");
    JLabel passwordLabel = new JLabel("Password: ");
    JTextField usernameField = new JTextField(20);
    JPasswordField passwordField = new JPasswordField(20);
    usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U);
    usernameLabel.setLabelFor(usernameField);
    passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P);
    passwordLabel.setLabelFor(passwordField);
    getContentPane().add(usernameLabel);
    getContentPane().add(usernameField);
    getContentPane().add(passwordLabel);
    getContentPane().add(passwordField);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Auto complete TextField

   
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.util.List;
import javax.swing.JTextField;
import javax.swing.text.*;
public class jexpAutoTextField extends JTextField {
  class AutoDocument extends PlainDocument {
    public void replace(int i, int j, String s, AttributeSet attributeset)
        throws BadLocationException {
      super.remove(i, j);
      insertString(i, s, attributeset);
    }
    public void insertString(int i, String s, AttributeSet attributeset)
        throws BadLocationException {
      if (s == null || "".equals(s))
        return;
      String s1 = getText(0, i);
      String s2 = getMatch(s1 + s);
      int j = (i + s.length()) - 1;
      if (isStrict && s2 == null) {
        s2 = getMatch(s1);
        j--;
      } else if (!isStrict && s2 == null) {
        super.insertString(i, s, attributeset);
        return;
      }
      if (autoComboBox != null && s2 != null)
        autoComboBox.setSelectedValue(s2);
      super.remove(0, getLength());
      super.insertString(0, s2, attributeset);
      setSelectionStart(j + 1);
      setSelectionEnd(getLength());
    }
    public void remove(int i, int j) throws BadLocationException {
      int k = getSelectionStart();
      if (k > 0)
        k--;
      String s = getMatch(getText(0, k));
      if (!isStrict && s == null) {
        super.remove(i, j);
      } else {
        super.remove(0, getLength());
        super.insertString(0, s, null);
      }
      if (autoComboBox != null && s != null)
        autoComboBox.setSelectedValue(s);
      try {
        setSelectionStart(k);
        setSelectionEnd(getLength());
      } catch (Exception exception) {
      }
    }
  }
  public jexpAutoTextField(List list) {
    isCaseSensitive = false;
    isStrict = true;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      init();
      return;
    }
  }
  jexpAutoTextField(List list, jexpAutoComboBox b) {
    isCaseSensitive = false;
    isStrict = true;
    autoComboBox = null;
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      autoComboBox = b;
      init();
      return;
    }
  }
  private void init() {
    setDocument(new AutoDocument());
    if (isStrict && dataList.size() > 0)
      setText(dataList.get(0).toString());
  }
  private String getMatch(String s) {
    for (int i = 0; i < dataList.size(); i++) {
      String s1 = dataList.get(i).toString();
      if (s1 != null) {
        if (!isCaseSensitive
            && s1.toLowerCase().startsWith(s.toLowerCase()))
          return s1;
        if (isCaseSensitive && s1.startsWith(s))
          return s1;
      }
    }
    return null;
  }
  public void replaceSelection(String s) {
    AutoDocument _lb = (AutoDocument) getDocument();
    if (_lb != null)
      try {
        int i = Math.min(getCaret().getDot(), getCaret().getMark());
        int j = Math.max(getCaret().getDot(), getCaret().getMark());
        _lb.replace(i, j - i, s, null);
      } catch (Exception exception) {
      }
  }
  public boolean isCaseSensitive() {
    return isCaseSensitive;
  }
  public void setCaseSensitive(boolean flag) {
    isCaseSensitive = flag;
  }
  public boolean isStrict() {
    return isStrict;
  }
  public void setStrict(boolean flag) {
    isStrict = flag;
  }
  public List getDataList() {
    return dataList;
  }
  public void setDataList(List list) {
    if (list == null) {
      throw new IllegalArgumentException("values can not be null");
    } else {
      dataList = list;
      return;
    }
  }
  private List dataList;
  private boolean isCaseSensitive;
  private boolean isStrict;
  private jexpAutoComboBox autoComboBox;
}
import java.awt.event.ItemEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class jexpAutoComboBox extends JComboBox {
  private class AutoTextFieldEditor extends BasicComboBoxEditor {
    private jexpAutoTextField getAutoTextFieldEditor() {
      return (jexpAutoTextField) editor;
    }
    AutoTextFieldEditor(java.util.List list) {
      editor = new jexpAutoTextField(list, jexpAutoComboBox.this);
    }
  }
  public jexpAutoComboBox(java.util.List list) {
    isFired = false;
    autoTextFieldEditor = new AutoTextFieldEditor(list);
    setEditable(true);
    setModel(new DefaultComboBoxModel(list.toArray()) {
      protected void fireContentsChanged(Object obj, int i, int j) {
        if (!isFired)
          super.fireContentsChanged(obj, i, j);
      }
    });
    setEditor(autoTextFieldEditor);
  }
  public boolean isCaseSensitive() {
    return autoTextFieldEditor.getAutoTextFieldEditor().isCaseSensitive();
  }
  public void setCaseSensitive(boolean flag) {
    autoTextFieldEditor.getAutoTextFieldEditor().setCaseSensitive(flag);
  }
  public boolean isStrict() {
    return autoTextFieldEditor.getAutoTextFieldEditor().isStrict();
  }
  public void setStrict(boolean flag) {
    autoTextFieldEditor.getAutoTextFieldEditor().setStrict(flag);
  }
  public java.util.List getDataList() {
    return autoTextFieldEditor.getAutoTextFieldEditor().getDataList();
  }
  public void setDataList(java.util.List list) {
    autoTextFieldEditor.getAutoTextFieldEditor().setDataList(list);
    setModel(new DefaultComboBoxModel(list.toArray()));
  }
  void setSelectedValue(Object obj) {
    if (isFired) {
      return;
    } else {
      isFired = true;
      setSelectedItem(obj);
      fireItemStateChanged(new ItemEvent(this, 701, selectedItemReminder,
          1));
      isFired = false;
      return;
    }
  }
  protected void fireActionEvent() {
    if (!isFired)
      super.fireActionEvent();
  }
  private AutoTextFieldEditor autoTextFieldEditor;
  private boolean isFired;
}





Based on JTextField content, enable or disable a JButton

    
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class Main {
  JButton button = new JButton("foo");
  JTextField textfield = new JTextField(10);
  Document document;
  public Main() {
    document = textfield.getDocument();
    document.addDocumentListener(new JButtonStateController());
  }
  class JButtonStateController implements DocumentListener {
    JButtonStateController() {
    }
    public void changedUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void insertUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void removeUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void disableIfEmpty(DocumentEvent e) {
      button.setEnabled(e.getDocument().getLength() > 0);
    }
  }
}





Bounded TextField

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class BoundedTextField extends JTextField implements
    BoundedPlainDocument.InsertErrorListener {
  public BoundedTextField() {
    this(null, 0, 0);
  }
  public BoundedTextField(String text, int columns, int maxLength) {
    super(null, text, columns);
    if (text != null && maxLength == 0) {
      maxLength = text.length();
    }
    BoundedPlainDocument plainDoc = (BoundedPlainDocument) getDocument();
    plainDoc.setMaxLength(maxLength);
    plainDoc.addInsertErrorListener(this);
  }
  public BoundedTextField(int columns, int maxLength) {
    this(null, columns, maxLength);
  }
  public BoundedTextField(String text, int maxLength) {
    this(text, 0, maxLength);
  }
  public void setMaxLength(int maxLength) {
    ((BoundedPlainDocument) getDocument()).setMaxLength(maxLength);
  }
  public int getMaxLength() {
    return ((BoundedPlainDocument) getDocument()).getMaxLength();
  }
  // Override to handle insertion error
  public void insertFailed(BoundedPlainDocument doc, int offset, String str,
      AttributeSet a) {
    // By default, just beep
    Toolkit.getDefaultToolkit().beep();
  }
  // Method to create default model
  protected Document createDefaultModel() {
    return new BoundedPlainDocument();
  }
  // Test code
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Bounded Text Field Example");
    BoundedTextField tf = new BoundedTextField(10, 32);
    JLabel l = new JLabel("Type up to 32 characters: ");
    f.getContentPane().add(tf, "East");
    f.getContentPane().add(l, "West");
    f.pack();
    f.setVisible(true);
  }
}
class BoundedPlainDocument extends PlainDocument {
  public BoundedPlainDocument() {
    // Default constructor - must use setMaxLength later
    this.maxLength = 0;
  }
  public BoundedPlainDocument(int maxLength) {
    this.maxLength = maxLength;
  }
  public BoundedPlainDocument(AbstractDocument.Content content, int maxLength) {
    super(content);
    if (content.length() > maxLength) {
      throw new IllegalArgumentException(
          "Initial content larger than maximum size");
    }
    this.maxLength = maxLength;
  }
  public void setMaxLength(int maxLength) {
    if (getLength() > maxLength) {
      throw new IllegalArgumentException(
          "Current content larger than new maximum size");
    }
    this.maxLength = maxLength;
  }
  public int getMaxLength() {
    return maxLength;
  }
  public void insertString(int offset, String str, AttributeSet a)
      throws BadLocationException {
    if (str == null) {
      return;
    }
    // Note: be careful here - the content always has a
    // trailing newline, which should not be counted!
    int capacity = maxLength + 1 - getContent().length();
    if (capacity >= str.length()) {
      // It all fits
      super.insertString(offset, str, a);
    } else {
      // It doesn"t all fit. Add as much as we can.
      if (capacity > 0) {
        super.insertString(offset, str.substring(0, capacity), a);
      }
      // Finally, signal an error.
      if (errorListener != null) {
        errorListener.insertFailed(this, offset, str, a);
      }
    }
  }
  public void addInsertErrorListener(InsertErrorListener l) {
    if (errorListener == null) {
      errorListener = l;
      return;
    }
    throw new IllegalArgumentException(
        "InsertErrorListener already registered");
  }
  public void removeInsertErrorListener(InsertErrorListener l) {
    if (errorListener == l) {
      errorListener = null;
    }
  }
  public interface InsertErrorListener {
    public abstract void insertFailed(BoundedPlainDocument doc, int offset,
        String str, AttributeSet a);
  }
  protected InsertErrorListener errorListener; // Unicast listener
  protected int maxLength;
}





Create the textfield

   
import javax.swing.*;
import java.awt.*;
public class JTextFieldTest extends JFrame {
  public JTextFieldTest() {
    super("JTextField Test");
    getContentPane().setLayout(new FlowLayout());
    JTextField textField1 = new JTextField("1", 1);
    JTextField textField2 = new JTextField("22", 2);
    JTextField textField3 = new JTextField("333", 3);
    getContentPane().add(textField1);
    getContentPane().add(textField2);
    getContentPane().add(textField3);
    setSize(300, 170);
    setVisible(true);
  }
  public static void main(String argv[]) {
    new JTextFieldTest();
  }
}





Cut, paste, and copy in a JTextField under program control.

    
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main {
  JTextField jtf = new JTextField(15);
  JButton jbtnCut = new JButton("Cut");
  JButton jbtnPaste = new JButton("Paste");
  JButton jbtnCopy = new JButton("Copy");
  public Main() {
    JFrame jfrm = new JFrame("Cut, Copy, and Paste");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(230, 150);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    jbtnCut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        jtf.cut();
        update();
      }
    });
    jbtnPaste.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        jtf.paste();
        update();
      }
    });
    jbtnCopy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent le) {
        jtf.copy();
        update();
      }
    });
    jtf.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent ce) {
        update();
      }
    });
    jfrm.add(jtf);
    jfrm.add(jbtnCut);
    jfrm.add(jbtnPaste);
    jfrm.add(jbtnCopy);
    jfrm.setVisible(true);
  }
  private void update() {
    System.out.println("All text: " + jtf.getText());
    if (jtf.getSelectedText() != null)
      System.out.println("Selected text: " + jtf.getSelectedText());
    else
      System.out.println("Selected text: ");
  }
  public static void main(String args[]) {
    new Main();
  }
}





EditabilityExample

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
public class EditabilityExample {
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Editability Example");
    f.getContentPane().setLayout(
        new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
    f.getContentPane().add(firstField);
    JTextField tf = new JTextField("A read-only text field", 20);
    tf.setEditable(false);
    f.getContentPane().add(tf);
    JTextArea ta = new JTextArea("An editable\ntext area", 2, 20);
    ta.setBorder(BorderFactory.createLoweredBevelBorder());
    f.getContentPane().add(ta);
    ta = new JTextArea("A read-only\ntext area", 2, 20);
    ta.setBorder(BorderFactory.createLoweredBevelBorder());
    ta.setEditable(false);
    f.getContentPane().add(ta);
    f.pack();
    f.show();
    if (args.length == 1 && args[0].equals("disable")) {
      // Toggle the enabled state of the first
      // text field every 10 seconds
      Timer t = new Timer(10000, new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
          firstField.setEnabled(!firstField.isEnabled());
          firstField.setText(firstFieldText
              + (firstField.isEnabled() ? "" : " (disabled)"));
        }
      });
      t.start();
    }
  }
  final static String firstFieldText = "An editable text field";
  final static JTextField firstField = new JTextField(firstFieldText, 20);
}





extends JTextField to create integer JTextField

   
/*
 * Copyright (C) 2001-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.awt.Toolkit;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
 * This class is a <CODE>TextField</CODE> that only allows integer
 * values to be entered into it.
 *
 * @author 
 */
public class IntegerField extends JTextField
{
  /**
   * Default ctor.
   */
  public IntegerField()
  {
    super();
  }
  /**
   * Ctor specifying the field width.
   *
   * @param cols  Number of columns.
   */
  public IntegerField(int cols)
  {
    super(cols);
  }
  /**
   * Retrieve the contents of this field as an <TT>int</TT>.
   *
   * @return  the contents of this field as an <TT>int</TT>.
   */
  public int getInt()
  {
    final String text = getText();
    if (text == null || text.length() == 0)
    {
      return 0;
    }
    return Integer.parseInt(text);
  }
  /**
   * Set the contents of this field to the passed <TT>int</TT>.
   *
   * @param value The new value for this field.
   */
  public void setInt(int value)
  {
    setText(String.valueOf(value));
  }
  /**
   * Create a new document model for this control that only accepts
   * integral values.
   *
   * @return  The new document model.
   */
  protected Document createDefaultModel()
  {
    return new IntegerDocument();
  }
  /**
   * This document only allows integral values to be added to it.
   */
  static class IntegerDocument extends PlainDocument
  {
    public void insertString(int offs, String str, AttributeSet a)
      throws BadLocationException
    {
      if (str != null)
      {
        try
        {
          Integer.decode(str);
          super.insertString(offs, str, a);
        }
        catch (NumberFormatException ex)
        {
          Toolkit.getDefaultToolkit().beep();
        }
      }
    }
  }
}





FieldEdit - an Applet to validate data as it"s being entered

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.applet.Applet;
import java.awt.Label;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
/**
 * FieldEdit - an Applet to validate data as it"s being entered.
 * 
 * Not very general: a 52 minute hack to show the mechanics of editing.
 * 
 * Does try to leave the cursor in exactly the right position.
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 * @author Bjorn Gudehus, gothic@celestica.ru
 */
public class FieldEdit extends Applet {
  /** The label to display the type of thing we"re editing */
  private Label myLabel;
  /** The textfield to enter */
  private TextField textField;
  /** Init() is an Applet method used to set up the GUI and listeners */
  public void init() {
    add(myLabel = new Label("Hex:"));
    add(textField = new TextField(10));
    textField.addTextListener(new TextListener() {
      public void textValueChanged(TextEvent ev) {
        int caret = -1;
        TextField tf = FieldEdit.this.textField;
        String s = tf.getText();
        StringBuffer sb = new StringBuffer();
        System.out.println("Text->" + s);
        for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
          if (Character.digit(c, 16) >= 0)
            sb.append(c);
          else
            caret = tf.getCaretPosition() - 1;
        }
        if (caret >= 0) {
          tf.setText(sb.toString());
          tf.setCaretPosition(caret);
          Toolkit.getDefaultToolkit().beep();
        }
      }
    });
  }
}





Firing Item Events

    
import java.awt.ItemSelectable;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;
public class Main {
  public static void main(String[] argv) throws Exception {
    MyComponent component = new MyComponent();
    JFrame f = new JFrame();
    f.add(component);
    f.setSize(300, 300);
    f.setVisible(true);
  }
}
class MyComponent extends JTextField implements ItemSelectable {
  protected EventListenerList listenerList = new EventListenerList();
  public Object[] getSelectedObjects() {
    return new String[] { "a", "b", "c" };
  }
  public void addItemListener(ItemListener l) {
    listenerList.add(ItemListener.class, l);
  }
  public void removeItemListener(ItemListener l) {
    listenerList.remove(ItemListener.class, l);
  }
  void fireItemEvent(Object item, boolean sel) {
    ItemEvent evt = new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, item,
        sel ? ItemEvent.SELECTED : ItemEvent.DESELECTED);
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length - 2; i += 2) {
      if (listeners[i] == ItemListener.class) {
        ((ItemListener) listeners[i + 1]).itemStateChanged(evt);
      }
    }
  }
}





JTextField Alignment Sample

   
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class AlignmentSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Alignment Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = frame.getContentPane();
    content.setLayout(new GridLayout(0, 1));
    JTextField textField = new JTextField("Left");
    textField.setHorizontalAlignment(JTextField.LEFT);
    content.add(textField);
    textField = new JTextField("Center");
    textField.setHorizontalAlignment(JTextField.CENTER);
    content.add(textField);
    textField = new JTextField("Right");
    textField.setHorizontalAlignment(JTextField.RIGHT);
    content.add(textField);
    textField = new JTextField("Leading");
    textField.setHorizontalAlignment(JTextField.LEADING);
    content.add(textField);
    textField = new JTextField("Trailing");
    textField.setHorizontalAlignment(JTextField.TRAILING);
    content.add(textField);
    frame.pack();
    frame.setSize(250, (int) frame.getSize().getHeight());
    frame.setVisible(true);
  }
}





JTextField Max Length

   
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class JTextFieldMaxLength extends JTextField{
  public JTextFieldMaxLength(int length){
    this(null,length);
  }
  public JTextFieldMaxLength(String text, int length){
    super(new PlainDocumentMaxLength(length),text,length);
  }
}
class PlainDocumentMaxLength extends PlainDocument{
  private int maxLength;
  public PlainDocumentMaxLength(int maxLength) {
    this.maxLength = maxLength;
  }
  public void insertString (int offset, String str, AttributeSet a)
    throws BadLocationException { if (getLength() + str.length() > maxLength) { 
    // Toolkit.getDefaultToolkit().beep();
    }else{
    super.insertString(offset,str,a);
    }
  }
}





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 == 0 ? "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 = (JTextComponent) input;
        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(250, 150);
    frame.setVisible(true);
  }
}





JTextField Verifier Sample

   
import java.awt.BorderLayout;
import java.awt.Container;
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();
    JTextField textField3 = 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);
    textField3.setInputVerifier(verifier);
    Container contentPane = frame.getContentPane();
    contentPane.add(textField1, BorderLayout.NORTH);
    contentPane.add(textField2, BorderLayout.CENTER);
    contentPane.add(textField3, BorderLayout.SOUTH);
    frame.setSize(300, 100);
    frame.setVisible(true);
  }
}





Limit JTextField input to a maximum length

    
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
class JTextFieldLimit extends PlainDocument {
  private int limit;
  JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
  }
  JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
  }
  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null)
      return;
    if ((getLength() + str.length()) <= limit) {
      super.insertString(offset, str, attr);
    }
  }
}
public class Main extends JFrame {
  JTextField textfield1;
  JLabel label1;
  public void init() {
    setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    add(label1);
    add(textfield1);
    textfield1.setDocument(new JTextFieldLimit(10));
    
    setSize(300,300);
    setVisible(true);
  }
}





Make a Text Field two columns wide

   
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] args) {
    JTextField tf = new JTextField("mm");
    tf.setPreferredSize(tf.getPreferredSize());
    tf.setText("");
    JPanel pHacked = new JPanel();
    pHacked.add(tf);
    JPanel pStock = new JPanel();
    pStock.add(new JTextField(2));
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new java.awt.GridLayout(0, 1));
    frame.add(pHacked);
    frame.add(pStock);
    frame.setSize(150, 150);
    frame.setVisible(true);
    tf.requestFocus();
  }
}





Make sure that my JTextField has the focus when a JFrame is created

    
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class Main extends JFrame {
  JTextField field1 = new JTextField(10);;
  JTextField field2 = new JTextField(10);;
  JPanel panel = new JPanel();
  public Main() {
    panel.add(new JLabel("Field 1:"));
    panel.add(field1);
    panel.add(new JLabel("Field 2:"));
    panel.add(field2);
    getContentPane().add("Center", panel);
    addWindowListener(new WindowAdapter() {
      public void windowOpened(WindowEvent e) {
        field1.requestFocus();
      }
    });
    pack();
    setVisible(true);
  }
  public static void main(String[] argv) {
    new Main();
  }
}





Make sure that my Text field has the focus when a JFrame is created

    
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
class MyFrame extends JFrame {
  JTextField field1;
  public MyFrame() {
    field1 = new JTextField(10);
    getContentPane().add("Center", field1);
    addWindowListener(new WindowAdapter() {
      public void windowOpened(WindowEvent e) {
        field1.requestFocus();
      }
    });
    pack();
    setVisible(true);
  }
}
public class Main {
  public static void main(String[] argv) {
    MyFrame myFrame = new MyFrame();
  }
}





Make the ENTER key act like the TAB key

    
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
class MyTextField extends JTextField {
  MyTextField(int len) {
    super(len);
    addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent evt) {
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER)
          transferFocus();
      }
    });
  }
}





Modify horizontal alignment of text field at runtime

    
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] args) {
    final JTextField tf = new JTextField("press <enter>", 20);
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int old = tf.getHorizontalAlignment();
        if (old == JTextField.LEFT)
          tf.setHorizontalAlignment(JTextField.RIGHT);
        if (old == JTextField.RIGHT)
          tf.setHorizontalAlignment(JTextField.CENTER);
        if (old == JTextField.CENTER)
          tf.setHorizontalAlignment(JTextField.LEFT);
      }
    });
    JFrame frame = new JFrame("JTextFieldExample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new java.awt.FlowLayout());
    frame.getContentPane().add(tf);
    frame.setSize(275, 75);
    frame.setVisible(true);
    tf.requestFocus();
  }
}





Non Wrapping(Wrap) TextPane

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.ruponent;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.plaf.ruponentUI;
import javax.swing.text.StyledDocument;
public class NonWrappingTextPane extends JTextPane {
  public NonWrappingTextPane() {
    super();
  }
  public NonWrappingTextPane(StyledDocument doc) {
    super(doc);
  }
  // Override getScrollableTracksViewportWidth
  // to preserve the full width of the text
  public boolean getScrollableTracksViewportWidth() {
    Component parent = getParent();
    ComponentUI ui = getUI();
    return parent != null ? (ui.getPreferredSize(this).width <= parent
        .getSize().width) : true;
  }
  // Test method
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    String content = "The plaque on the Apollo 11 Lunar Module\n"
        + "\"Eagle\" reads:\n\n"
        + "\"Here men from the planet Earth first\n"
        + "set foot upon the Moon, July, 1969 AD\n"
        + "We came in peace for all mankind.\"\n\n"
        + "It is signed by the astronauts and the\n"
        + "President of the United States.";
    JFrame f = new JFrame("Non-wrapping Text Pane Example");
    JTextPane tp = new JTextPane();
    tp.setText(content);
    NonWrappingTextPane nwtp = new NonWrappingTextPane();
    nwtp.setText(content);
    f.getContentPane().setLayout(new GridLayout(2, 1));
    f.getContentPane().add(new JScrollPane(tp));
    f.getContentPane().add(new JScrollPane(nwtp));
    f.setSize(300, 200);
    f.setVisible(true);
  }
}





Numeric TextField

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import javax.swing.text.AbstractDocument.Content;
public class NumericTextField extends JTextField implements
    NumericPlainDocument.InsertErrorListener {
  public NumericTextField() {
    this(null, 0, null);
  }
  public NumericTextField(String text, int columns, DecimalFormat format) {
    super(null, text, columns);
    NumericPlainDocument numericDoc = (NumericPlainDocument) getDocument();
    if (format != null) {
      numericDoc.setFormat(format);
    }
    numericDoc.addInsertErrorListener(this);
  }
  public NumericTextField(int columns, DecimalFormat format) {
    this(null, columns, format);
  }
  public NumericTextField(String text) {
    this(text, 0, null);
  }
  public NumericTextField(String text, int columns) {
    this(text, columns, null);
  }
  public void setFormat(DecimalFormat format) {
    ((NumericPlainDocument) getDocument()).setFormat(format);
  }
  public DecimalFormat getFormat() {
    return ((NumericPlainDocument) getDocument()).getFormat();
  }
  public void formatChanged() {
    // Notify change of format attributes.
    setFormat(getFormat());
  }
  // Methods to get the field value
  public Long getLongValue() throws ParseException {
    return ((NumericPlainDocument) getDocument()).getLongValue();
  }
  public Double getDoubleValue() throws ParseException {
    return ((NumericPlainDocument) getDocument()).getDoubleValue();
  }
  public Number getNumberValue() throws ParseException {
    return ((NumericPlainDocument) getDocument()).getNumberValue();
  }
  // Methods to install numeric values
  public void setValue(Number number) {
    setText(getFormat().format(number));
  }
  public void setValue(long l) {
    setText(getFormat().format(l));
    ;
  }
  public void setValue(double d) {
    setText(getFormat().format(d));
  }
  public void normalize() throws ParseException {
    // format the value according to the format string
    setText(getFormat().format(getNumberValue()));
  }
  // Override to handle insertion error
  public void insertFailed(NumericPlainDocument doc, int offset, String str,
      AttributeSet a) {
    // By default, just beep
    Toolkit.getDefaultToolkit().beep();
  }
  // Method to create default model
  protected Document createDefaultModel() {
    return new NumericPlainDocument();
  }
  // Test code
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    DecimalFormat format = new DecimalFormat("#,###.###");
    format.setGroupingUsed(true);
    format.setGroupingSize(3);
    format.setParseIntegerOnly(false);
    JFrame f = new JFrame("Numeric Text Field Example");
    final NumericTextField tf = new NumericTextField(10, format);
    tf.setValue((double) 123456.789);
    JLabel lbl = new JLabel("Type a number: ");
    f.getContentPane().add(tf, "East");
    f.getContentPane().add(lbl, "West");
    tf.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        try {
          tf.normalize();
          Long l = tf.getLongValue();
          System.out.println("Value is (Long)" + l);
        } catch (ParseException e1) {
          try {
            Double d = tf.getDoubleValue();
            System.out.println("Value is (Double)" + d);
          } catch (ParseException e2) {
            System.out.println(e2);
          }
        }
      }
    });
    f.pack();
    f.setVisible(true);
  }
}
class NumericPlainDocument extends PlainDocument {
  public NumericPlainDocument() {
    setFormat(null);
  }
  public NumericPlainDocument(DecimalFormat format) {
    setFormat(format);
  }
  public NumericPlainDocument(AbstractDocument.Content content,
      DecimalFormat format) {
    super(content);
    setFormat(format);
    try {
      format
          .parseObject(content.getString(0, content.length()),
              parsePos);
    } catch (Exception e) {
      throw new IllegalArgumentException(
          "Initial content not a valid number");
    }
    if (parsePos.getIndex() != content.length() - 1) {
      throw new IllegalArgumentException(
          "Initial content not a valid number");
    }
  }
  public void setFormat(DecimalFormat fmt) {
    this.format = fmt != null ? fmt : (DecimalFormat) defaultFormat.clone();
    decimalSeparator = format.getDecimalFormatSymbols()
        .getDecimalSeparator();
    groupingSeparator = format.getDecimalFormatSymbols()
        .getGroupingSeparator();
    positivePrefix = format.getPositivePrefix();
    positivePrefixLen = positivePrefix.length();
    negativePrefix = format.getNegativePrefix();
    negativePrefixLen = negativePrefix.length();
    positiveSuffix = format.getPositiveSuffix();
    positiveSuffixLen = positiveSuffix.length();
    negativeSuffix = format.getNegativeSuffix();
    negativeSuffixLen = negativeSuffix.length();
  }
  public DecimalFormat getFormat() {
    return format;
  }
  public Number getNumberValue() throws ParseException {
    try {
      String content = getText(0, getLength());
      parsePos.setIndex(0);
      Number result = format.parse(content, parsePos);
      if (parsePos.getIndex() != getLength()) {
        throw new ParseException("Not a valid number: " + content, 0);
      }
      return result;
    } catch (BadLocationException e) {
      throw new ParseException("Not a valid number", 0);
    }
  }
  public Long getLongValue() throws ParseException {
    Number result = getNumberValue();
    if ((result instanceof Long) == false) {
      throw new ParseException("Not a valid long", 0);
    }
    return (Long) result;
  }
  public Double getDoubleValue() throws ParseException {
    Number result = getNumberValue();
    if ((result instanceof Long) == false
        && (result instanceof Double) == false) {
      throw new ParseException("Not a valid double", 0);
    }
    if (result instanceof Long) {
      result = new Double(result.doubleValue());
    }
    return (Double) result;
  }
  public void insertString(int offset, String str, AttributeSet a)
      throws BadLocationException {
    if (str == null || str.length() == 0) {
      return;
    }
    Content content = getContent();
    int length = content.length();
    int originalLength = length;
    parsePos.setIndex(0);
    // Create the result of inserting the new data,
    // but ignore the trailing newline
    String targetString = content.getString(0, offset) + str
        + content.getString(offset, length - offset - 1);
    // Parse the input string and check for errors
    do {
      boolean gotPositive = targetString.startsWith(positivePrefix);
      boolean gotNegative = targetString.startsWith(negativePrefix);
      length = targetString.length();
      // If we have a valid prefix, the parse fails if the
      // suffix is not present and the error is reported
      // at index 0. So, we need to add the appropriate
      // suffix if it is not present at this point.
      if (gotPositive == true || gotNegative == true) {
        String suffix;
        int suffixLength;
        int prefixLength;
        if (gotPositive == true && gotNegative == true) {
          // This happens if one is the leading part of
          // the other - e.g. if one is "(" and the other "(("
          if (positivePrefixLen > negativePrefixLen) {
            gotNegative = false;
          } else {
            gotPositive = false;
          }
        }
        if (gotPositive == true) {
          suffix = positiveSuffix;
          suffixLength = positiveSuffixLen;
          prefixLength = positivePrefixLen;
        } else {
          // Must have the negative prefix
          suffix = negativeSuffix;
          suffixLength = negativeSuffixLen;
          prefixLength = negativePrefixLen;
        }
        // If the string consists of the prefix alone,
        // do nothing, or the result won"t parse.
        if (length == prefixLength) {
          break;
        }
        // We can"t just add the suffix, because part of it
        // may already be there. For example, suppose the
        // negative prefix is "(" and the negative suffix is
        // "$)". If the user has typed "(345$", then it is not
        // correct to add "$)". Instead, only the missing part
        // should be added, in this case ")".
        if (targetString.endsWith(suffix) == false) {
          int i;
          for (i = suffixLength - 1; i > 0; i--) {
            if (targetString
                .regionMatches(length - i, suffix, 0, i)) {
              targetString += suffix.substring(i);
              break;
            }
          }
          if (i == 0) {
            // None of the suffix was present
            targetString += suffix;
          }
          length = targetString.length();
        }
      }
      format.parse(targetString, parsePos);
      int endIndex = parsePos.getIndex();
      if (endIndex == length) {
        break; // Number is acceptable
      }
      // Parse ended early
      // Since incomplete numbers don"t always parse, try
      // to work out what went wrong.
      // First check for an incomplete positive prefix
      if (positivePrefixLen > 0 && endIndex < positivePrefixLen
          && length <= positivePrefixLen
          && targetString.regionMatches(0, positivePrefix, 0, length)) {
        break; // Accept for now
      }
      // Next check for an incomplete negative prefix
      if (negativePrefixLen > 0 && endIndex < negativePrefixLen
          && length <= negativePrefixLen
          && targetString.regionMatches(0, negativePrefix, 0, length)) {
        break; // Accept for now
      }
      // Allow a number that ends with the group
      // or decimal separator, if these are in use
      char lastChar = targetString.charAt(originalLength - 1);
      int decimalIndex = targetString.indexOf(decimalSeparator);
      if (format.isGroupingUsed() && lastChar == groupingSeparator
          && decimalIndex == -1) {
        // Allow a "," but only in integer part
        break;
      }
      if (format.isParseIntegerOnly() == false
          && lastChar == decimalSeparator
          && decimalIndex == originalLength - 1) {
        // Allow a ".", but only one
        break;
      }
      // No more corrections to make: must be an error
      if (errorListener != null) {
        errorListener.insertFailed(this, offset, str, a);
      }
      return;
    } while (true == false);
    // Finally, add to the model
    super.insertString(offset, str, a);
  }
  public void addInsertErrorListener(InsertErrorListener l) {
    if (errorListener == null) {
      errorListener = l;
      return;
    }
    throw new IllegalArgumentException(
        "InsertErrorListener already registered");
  }
  public void removeInsertErrorListener(InsertErrorListener l) {
    if (errorListener == l) {
      errorListener = null;
    }
  }
  public interface InsertErrorListener {
    public abstract void insertFailed(NumericPlainDocument doc, int offset,
        String str, AttributeSet a);
  }
  protected InsertErrorListener errorListener;
  protected DecimalFormat format;
  protected char decimalSeparator;
  protected char groupingSeparator;
  protected String positivePrefix;
  protected String negativePrefix;
  protected int positivePrefixLen;
  protected int negativePrefixLen;
  protected String positiveSuffix;
  protected String negativeSuffix;
  protected int positiveSuffixLen;
  protected int negativeSuffixLen;
  protected ParsePosition parsePos = new ParsePosition(0);
  protected static DecimalFormat defaultFormat = new DecimalFormat();
}





Overwritable TextField

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.plaf.TextUI;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.TextAction;
public class OverwritableTextField extends JTextField {
  public OverwritableTextField() {
    this(null, null, 0);
  }
  public OverwritableTextField(String text) {
    this(null, text, 0);
  }
  public OverwritableTextField(int columns) {
    this(null, null, columns);
  }
  public OverwritableTextField(String text, int columns) {
    this(null, text, columns);
  }
  public OverwritableTextField(Document doc, String text, int columns) {
    super(doc, text, columns);
    overwriteCaret = new OverwriteCaret();
    super.setCaret(overwriting ? overwriteCaret : insertCaret);
  }
  public void setKeymap(Keymap map) {
    if (map == null) {
      super.setKeymap(null);
      sharedKeymap = null;
      return;
    }
    if (getKeymap() == null) {
      if (sharedKeymap == null) {
        // Switch keymaps. Add extra bindings.
        removeKeymap(keymapName);
        sharedKeymap = addKeymap(keymapName, map);
        loadKeymap(sharedKeymap, bindings, defaultActions);
      }
      map = sharedKeymap;
    }
    super.setKeymap(map);
  }
  public void replaceSelection(String content) {
    Document doc = getDocument();
    if (doc != null) {
      // If we are not overwriting, just do the
      // usual insert. Also, if there is a selection,
      // just overwrite that (and that only).
      if (overwriting == true && getSelectionStart() == getSelectionEnd()) {
        // Overwrite and no selection. Remove
        // the stretch that we will overwrite,
        // then use the usual code to insert the
        // new text.
        int insertPosition = getCaretPosition();
        int overwriteLength = doc.getLength() - insertPosition;
        int length = content.length();
        if (overwriteLength > length) {
          overwriteLength = length;
        }
        // Remove the range being overwritten
        try {
          doc.remove(insertPosition, overwriteLength);
        } catch (BadLocationException e) {
          // Won"t happen
        }
      }
    }
    super.replaceSelection(content);
  }
  // Change the global overwriting mode
  public static void setOverwriting(boolean overwriting) {
    OverwritableTextField.overwriting = overwriting;
  }
  public static boolean isOverwriting() {
    return overwriting;
  }
  // Configuration of the insert caret
  public void setCaret(Caret caret) {
    insertCaret = caret;
  }
  // Allow configuration of a new
  // overwrite caret.
  public void setOverwriteCaret(Caret caret) {
    overwriteCaret = caret;
  }
  public Caret getOverwriteCaret() {
    return overwriteCaret;
  }
  // Caret switching
  public void processFocusEvent(FocusEvent evt) {
    if (evt.getID() == FocusEvent.FOCUS_GAINED) {
      selectCaret();
    }
    super.processFocusEvent(evt);
  }
  protected void selectCaret() {
    // Select the appropriate caret for the
    // current overwrite mode.
    Caret newCaret = overwriting ? overwriteCaret : insertCaret;
    if (newCaret != getCaret()) {
      Caret caret = getCaret();
      int mark = caret.getMark();
      int dot = caret.getDot();
      caret.setVisible(false);
      super.setCaret(newCaret);
      newCaret.setDot(mark);
      newCaret.moveDot(dot);
      newCaret.setVisible(true);
    }
  }
  protected Caret overwriteCaret;
  protected Caret insertCaret;
  protected static boolean overwriting = true;
  public static final String toggleOverwriteAction = "toggle-overwrite";
  protected static Keymap sharedKeymap;
  protected static final String keymapName = "OverwriteMap";
  protected static final Action[] defaultActions = { new ToggleOverwriteAction() };
  protected static JTextComponent.KeyBinding[] bindings = { new JTextComponent.KeyBinding(
      KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
      toggleOverwriteAction) };
  // Insert/overwrite toggling action
  public static class ToggleOverwriteAction extends TextAction {
    ToggleOverwriteAction() {
      super(toggleOverwriteAction);
    }
    public void actionPerformed(ActionEvent evt) {
      OverwritableTextField.setOverwriting(!OverwritableTextField
          .isOverwriting());
      JTextComponent target = getFocusedComponent();
      if (target instanceof OverwritableTextField) {
        OverwritableTextField field = (OverwritableTextField) target;
        field.selectCaret();
      }
    }
  }
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Overwrite test");
    OverwritableTextField tf = new OverwritableTextField(20);
    f.getContentPane().add(tf, "North");
    tf = new OverwritableTextField(20);
    f.getContentPane().add(tf, "South");
    f.pack();
    f.setVisible(true);
  }
}
class OverwriteCaret extends DefaultCaret {
  protected synchronized void damage(Rectangle r) {
    if (r != null) {
      try {
        JTextComponent comp = getComponent();
        TextUI mapper = comp.getUI();
        Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
        int width = r2.x - r.x;
        if (width == 0) {
          width = MIN_WIDTH;
        }
        comp.repaint(r.x, r.y, width, r.height);
        // Swing 1.1 beta 2 compat
        this.x = r.x;
        this.y = r.y;
        this.width = width;
        this.height = r.height;
      } catch (BadLocationException e) {
      }
    }
  }
  public void paint(Graphics g) {
    if (isVisible()) {
      try {
        JTextComponent comp = getComponent();
        TextUI mapper = comp.getUI();
        Rectangle r1 = mapper.modelToView(comp, getDot());
        Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
        g = g.create();
        g.setColor(comp.getForeground());
        g.setXORMode(comp.getBackground());
        int width = r2.x - r1.x;
        if (width == 0) {
          width = MIN_WIDTH;
        }
        g.fillRect(r1.x, r1.y, width, r1.height);
        g.dispose();
      } catch (BadLocationException e) {
      }
    }
  }
  protected static final int MIN_WIDTH = 8;
}





Passive TextField 1

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.text.Keymap;
public class PassiveTextField1 extends JTextField {
  public static void main(String[] args) {
    JFrame f = new JFrame("Passive Text Field");
    f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
    final JTextField ptf = new JTextField(32);
    JTextField tf = new JTextField(32);
    JPanel p = new JPanel();
    JButton b = new JButton("OK");
    p.add(b);
    f.getContentPane().add(ptf);
    f.getContentPane().add(tf);
    f.getContentPane().add(p);
    Keymap map = ptf.getKeymap(); // Gets the shared map
    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    map.removeKeyStrokeBinding(key);
    ActionListener l = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Action event from a text field");
      }
    };
    ptf.addActionListener(l);
    tf.addActionListener(l);
    // Make the button the default button
    f.getRootPane().setDefaultButton(b);
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Content of text field: <" + ptf.getText()
            + ">");
      }
    });
    f.pack();
    f.setVisible(true);
  }
}





Passive TextField 2

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.Document;
import javax.swing.text.Keymap;
public class PassiveTextField2 extends JTextField {
  public PassiveTextField2() {
    this(null, null, 0);
  }
  public PassiveTextField2(String text) {
    this(null, text, 0);
  }
  public PassiveTextField2(int columns) {
    this(null, null, columns);
  }
  public PassiveTextField2(String text, int columns) {
    this(null, text, columns);
  }
  public PassiveTextField2(Document doc, String text, int columns) {
    super(doc, text, columns);
  }
  public void setKeymap(Keymap map) {
    if (map == null) {
      // Uninstalling keymap.
      super.setKeymap(null);
      sharedKeymap = null;
      return;
    }
    if (getKeymap() == null) {
      if (sharedKeymap == null) {
        // Initial keymap, or first
        // keymap after L&F switch.
        // Generate a new keymap
        sharedKeymap = addKeymap(null, map.getResolveParent());
        KeyStroke[] strokes = map.getBoundKeyStrokes();
        for (int i = 0; i < strokes.length; i++) {
          Action a = map.getAction(strokes[i]);
          if (a.getValue(Action.NAME) == JTextField.notifyAction) {
            continue;
          }
          sharedKeymap.addActionForKeyStroke(strokes[i], a);
        }
      }
      map = sharedKeymap;
    }
    super.setKeymap(map);
  }
  protected static Keymap sharedKeymap;
  // Test method
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Passive Text Field");
    f.getContentPane().setLayout(
        new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
    final PassiveTextField2 ptf = new PassiveTextField2(32);
    JTextField tf = new JTextField(32);
    JPanel p = new JPanel();
    JButton b = new JButton("OK");
    p.add(b);
    f.getContentPane().add(ptf);
    f.getContentPane().add(tf);
    f.getContentPane().add(p);
    SwingUtilities.updateComponentTreeUI(f);
    ActionListener l = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Action event from a text field");
      }
    };
    ptf.addActionListener(l);
    tf.addActionListener(l);
    // Make the button the default button
    f.getRootPane().setDefaultButton(b);
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Content of text field: <" + ptf.getText()
            + ">");
      }
    });
    f.pack();
    f.setVisible(true);
  }
}





Passive TextField 3

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.Document;
public class PassiveTextField extends JTextField {
  public PassiveTextField() {
    this(null, null, 0);
  }
  public PassiveTextField(String text) {
    this(null, text, 0);
  }
  public PassiveTextField(int columns) {
    this(null, null, columns);
  }
  public PassiveTextField(String text, int columns) {
    this(null, text, columns);
  }
  public PassiveTextField(Document doc, String text, int columns) {
    super(doc, text, columns);
  }
  public void processComponentKeyEvent(KeyEvent evt) {
    switch (evt.getID()) {
    case KeyEvent.KEY_PRESSED:
    case KeyEvent.KEY_RELEASED:
      if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        return;
      }
      break;
    case KeyEvent.KEY_TYPED:
      if (evt.getKeyChar() == "\r") {
        return;
      }
      break;
    }
    super.processComponentKeyEvent(evt);
  }
  // Test method
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Passive Text Field");
    f.getContentPane().setLayout(
        new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
    final PassiveTextField ptf = new PassiveTextField(32);
    JTextField tf = new JTextField(32);
    JPanel p = new JPanel();
    JButton b = new JButton("OK");
    p.add(b);
    f.getContentPane().add(ptf);
    f.getContentPane().add(tf);
    f.getContentPane().add(p);
    ActionListener l = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Action event from a text field");
      }
    };
    ptf.addActionListener(l);
    tf.addActionListener(l);
    // Make the button the default button
    f.getRootPane().setDefaultButton(b);
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        System.out.println("Content of text field: <" + ptf.getText()
            + ">");
      }
    });
    f.pack();
    f.setVisible(true);
  }
}





Right justified JTextfield content

    
import javax.swing.JTextField;
public class Main{
  public static void main(String[] argv) {
    JTextField textfield = new JTextField(10);
    textfield.setHorizontalAlignment(JTextField.RIGHT);
  }
}





Right justified JTextField contents

    
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(200, 200);
    Container container = getContentPane();
    container.setLayout(new FlowLayout(FlowLayout.LEFT));
    JTextField textField = new JTextField(15);
    textField.setPreferredSize(new Dimension(100, 20));
    // Right justify the JTextField contents
    textField.setHorizontalAlignment(JTextField.RIGHT);
    container.add(textField);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Set the focus on a particular JTextField

    
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main {
  public static void main(String[] argv) throws Exception {
    final JTextField textfield = new JTextField(10);
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        textfield.requestFocus();
      }
    });
  }
}





Setting up a textfield and modifying its horizontal alignment at runtime

   
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly 
*/
// JTextFieldExample.java
//An example of setting up a textfield and modifying its horizontal alignment
//at runtime.
//
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class JTextFieldExample {
  public static void main(String[] args) {
    final JTextField tf = new JTextField("press <enter>", 20);
    tf.setHorizontalAlignment(JTextField.RIGHT);
    tf.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int old = tf.getHorizontalAlignment();
        if (old == JTextField.LEFT)
          tf.setHorizontalAlignment(JTextField.RIGHT);
        if (old == JTextField.RIGHT)
          tf.setHorizontalAlignment(JTextField.CENTER);
        if (old == JTextField.CENTER)
          tf.setHorizontalAlignment(JTextField.LEFT);
      }
    });
    JFrame frame = new JFrame("JTextFieldExample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new java.awt.FlowLayout());
    frame.getContentPane().add(tf);
    frame.setSize(275, 75);
    frame.setVisible(true);
    tf.requestFocus();
  }
}





Text Accelerator Example

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class TextAcceleratorExample {
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JLabel l;
    JTextField t;
    JButton b;
    JFrame f = new JFrame("Text Accelerator Example");
    Container cp = f.getContentPane();
    cp.setLayout(new GridBagLayout());
    cp.setBackground(UIManager.getColor("control"));
    GridBagConstraints c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = GridBagConstraints.RELATIVE;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.insets = new Insets(2, 2, 2, 2);
    c.anchor = GridBagConstraints.EAST;
    cp.add(l = new JLabel("Name:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("n");
    cp.add(l = new JLabel("House/Street:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("h");
    cp.add(l = new JLabel("City:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("c");
    cp.add(l = new JLabel("State/County:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("s");
    cp.add(l = new JLabel("Zip/Post code:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("z");
    cp.add(l = new JLabel("Telephone:", SwingConstants.RIGHT), c);
    l.setDisplayedMnemonic("t");
    cp.add(b = new JButton("Clear"), c);
    b.setMnemonic("l");
    c.gridx = 1;
    c.gridy = 0;
    c.weightx = 1.0;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("n");
    c.gridx = 1;
    c.gridy = GridBagConstraints.RELATIVE;
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("h");
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("c");
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("s");
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("z");
    cp.add(t = new JTextField(35), c);
    t.setFocusAccelerator("t");
    c.weightx = 0.0;
    c.fill = GridBagConstraints.NONE;
    cp.add(b = new JButton("OK"), c);
    b.setMnemonic("o");
    f.pack();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent evt) {
        System.exit(0);
      }
    });
    f.setVisible(true);
  }
}





TextField Elements

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/

import javax.swing.*;
import javax.swing.text.*;
public class TextFieldElements {
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Text Field Elements");
    JTextField tf = new JTextField(32);
    tf.setText("That"s one small step for man...");
    f.getContentPane().add(tf);
    f.pack();
    f.setVisible(true);
    ((AbstractDocument)tf.getDocument()).dump(System.out);
  }
}





TextField Look Ahead Example

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class LookAheadExample {
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Text Lookahead");
    StringArrayLookAhead lookAhead = new StringArrayLookAhead(values);
    LookAheadTextField tf = new LookAheadTextField(20, lookAhead);
    f.getContentPane().add(tf, "Center");
    f.pack();
    f.setVisible(true);
  }
  // The possible look-ahead values
  public static String[] values = new String[] { "aback", "abacus",
      "abandon", "abashed", "abate", "abdomen", "abide", "ability",
      "baby", "back", "backache", "backgammon" };
}
class LookAheadTextField extends JTextField {
  public LookAheadTextField() {
    this(0, null);
  }
  public LookAheadTextField(int columns) {
    this(columns, null);
  }
  public LookAheadTextField(int columns, TextLookAhead lookAhead) {
    super(columns);
    setLookAhead(lookAhead);
    addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        // Remove any existing selection
        setCaretPosition(getDocument().getLength());
      }
    });
    addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent evt) {
      }
      public void focusLost(FocusEvent evt) {
        if (evt.isTemporary() == false) {
          // Remove any existing selection
          setCaretPosition(getDocument().getLength());
        }
      }
    });
  }
  public void setLookAhead(TextLookAhead lookAhead) {
    this.lookAhead = lookAhead;
  }
  public TextLookAhead getLookAhead() {
    return lookAhead;
  }
  public void replaceSelection(String content) {
    super.replaceSelection(content);
    if (isEditable() == false || isEnabled() == false) {
      return;
    }
    Document doc = getDocument();
    if (doc != null && lookAhead != null) {
      try {
        String oldContent = doc.getText(0, doc.getLength());
        String newContent = lookAhead.doLookAhead(oldContent);
        if (newContent != null) {
          // Substitute the new content
          setText(newContent);
          // Highlight the added text
          setCaretPosition(newContent.length());
          moveCaretPosition(oldContent.length());
        }
      } catch (BadLocationException e) {
        // Won"t happen
      }
    }
  }
  protected TextLookAhead lookAhead;
  // The TextLookAhead interface
  public interface TextLookAhead {
    public String doLookAhead(String key);
  }
}
class StringArrayLookAhead implements LookAheadTextField.TextLookAhead {
  public StringArrayLookAhead() {
    values = new String[0];
  }
  public StringArrayLookAhead(String[] values) {
    this.values = values;
  }
  public void setValues(String[] values) {
    this.values = values;
  }
  public String[] getValues() {
    return values;
  }
  public String doLookAhead(String key) {
    int length = values.length;
    // Look for a string that starts with the key
    for (int i = 0; i < length; i++) {
      if (values[i].startsWith(key) == true) {
        return values[i];
      }
    }
    // No match found - return null
    return null;
  }
  protected String[] values;
}





Textfield only accepts numbers

   
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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(WindowEvent e) {
        System.exit(0);
      }
    });
    Container contentPane = getContentPane();
    JPanel p = new JPanel();
    intFiled = new IntTextField(12, 3);
    p.add(intFiled);
    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 createDefaultModel() {
    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");
        super.insertString(offs, str, a);
      } catch (NumberFormatException e) {
      }
    }
  }
}





Text fields and Java events

   
// : c14:TextFields.java
// Text fields and Java events.
// <applet code=TextFields width=375 height=125></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
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.PlainDocument;
public class TextFields extends JApplet {
  private JButton b1 = new JButton("Get Text"), b2 = new JButton("Set Text");
  private JTextField t1 = new JTextField(30), t2 = new JTextField(30),
      t3 = new JTextField(30);
  private String s = new String();
  private UpperCaseDocument ucd = new UpperCaseDocument();
  public void init() {
    t1.setDocument(ucd);
    ucd.addDocumentListener(new T1());
    b1.addActionListener(new B1());
    b2.addActionListener(new B2());
    DocumentListener dl = new T1();
    t1.addActionListener(new T1A());
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(b1);
    cp.add(b2);
    cp.add(t1);
    cp.add(t2);
    cp.add(t3);
  }
  class T1 implements DocumentListener {
    public void changedUpdate(DocumentEvent e) {
    }
    public void insertUpdate(DocumentEvent e) {
      t2.setText(t1.getText());
      t3.setText("Text: " + t1.getText());
    }
    public void removeUpdate(DocumentEvent e) {
      t2.setText(t1.getText());
    }
  }
  class T1A implements ActionListener {
    private int count = 0;
    public void actionPerformed(ActionEvent e) {
      t3.setText("t1 Action Event " + count++);
    }
  }
  class B1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (t1.getSelectedText() == null)
        s = t1.getText();
      else
        s = t1.getSelectedText();
      t1.setEditable(true);
    }
  }
  class B2 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      ucd.setUpperCase(false);
      t1.setText("Inserted by Button 2: " + s);
      ucd.setUpperCase(true);
      t1.setEditable(false);
    }
  }
  public static void main(String[] args) {
    run(new TextFields(), 375, 125);
  }
  public static void run(JApplet applet, int width, int height) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(applet);
    frame.setSize(width, height);
    applet.init();
    applet.start();
    frame.setVisible(true);
  }
  
}
class UpperCaseDocument extends PlainDocument {
  private boolean upperCase = true;
  public void setUpperCase(boolean flag) {
    upperCase = flag;
  }
  public void insertString(int offset, String str, AttributeSet attSet)
      throws BadLocationException {
    if (upperCase)
      str = str.toUpperCase();
    super.insertString(offset, str, attSet);
  }
} ///:~





TextFieldViews 2

   
/*
Core SWING Advanced Programming 
By Kim Topley
ISBN: 0 13 083292 8       
Publisher: Prentice Hall  
*/

import java.io.PrintStream;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
public class TextFieldViews {
  public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {}
  
    JFrame f = new JFrame("Text Field View");
    JTextField tf = new JTextField(32);
    tf.setText("That"s one small step for man...");
    f.getContentPane().add(tf);
    f.pack();
    f.setVisible(true);
    ViewDisplayer.displayViews(tf, System.out);
  }
}
class ViewDisplayer {
  public static void displayViews(JTextComponent comp, PrintStream out) {
    View rootView = comp.getUI().getRootView(comp);
    displayView(rootView, 0, comp.getDocument(), out);
  }
  public static void displayView(View view, int indent, Document doc,
      PrintStream out) {
    String name = view.getClass().getName();
    for (int i = 0; i < indent; i++) {
      out.print("\t");
    }
    int start = view.getStartOffset();
    int end = view.getEndOffset();
    out.println(name + "; offsets [" + start + ", " + end + "]");
    int viewCount = view.getViewCount();
    if (viewCount == 0) {
      int length = Math.min(32, end - start);
      try {
        String txt = doc.getText(start, length);
        for (int i = 0; i < indent + 1; i++) {
          out.print("\t");
        }
        out.println("[" + txt + "]");
      } catch (BadLocationException e) {
      }
    } else {
      for (int i = 0; i < viewCount; i++) {
        displayView(view.getView(i), indent + 1, doc, out);
      }
    }
  }
}





TextField with Constaints

   
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
public class RangeSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Range Example");
    Container content = frame.getContentPane();
    content.setLayout(new GridLayout(3, 2));
    content.add(new JLabel("Range: 0-255"));
    Document rangeOne = new IntegerRangeDocument(0, 255);
    JTextField textFieldOne = new JTextField();
    textFieldOne.setDocument(rangeOne);
    content.add(textFieldOne);
    content.add(new JLabel("Range: -100-100"));
    Document rangeTwo = new IntegerRangeDocument(-100, 100);
    JTextField textFieldTwo = new JTextField();
    textFieldTwo.setDocument(rangeTwo);
    content.add(textFieldTwo);
    content.add(new JLabel("Range: 1000-2000"));
    Document rangeThree = new IntegerRangeDocument(1000, 2000);
    JTextField textFieldThree = new JTextField();
    textFieldThree.setDocument(rangeThree);
    content.add(textFieldThree);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}
class IntegerRangeDocument extends PlainDocument {
  int minimum, maximum;
  int currentValue = 0;
  public IntegerRangeDocument(int minimum, int maximum) {
    this.minimum = minimum;
    this.maximum = maximum;
  }
  public int getValue() {
    return currentValue;
  }
  public void insertString(int offset, String string, AttributeSet attributes)
      throws BadLocationException {
    if (string == null) {
      return;
    } else {
      String newValue;
      int length = getLength();
      if (length == 0) {
        newValue = string;
      } else {
        String currentContent = getText(0, length);
        StringBuffer currentBuffer = new StringBuffer(currentContent);
        currentBuffer.insert(offset, string);
        newValue = currentBuffer.toString();
      }
      try {
        currentValue = checkInput(newValue);
        super.insertString(offset, string, attributes);
      } catch (Exception exception) {
        Toolkit.getDefaultToolkit().beep();
      }
    }
  }
  public void remove(int offset, int length) throws BadLocationException {
    int currentLength = getLength();
    String currentContent = getText(0, currentLength);
    String before = currentContent.substring(0, offset);
    String after = currentContent.substring(length + offset, currentLength);
    String newValue = before + after;
    try {
      currentValue = checkInput(newValue);
      super.remove(offset, length);
    } catch (Exception exception) {
      Toolkit.getDefaultToolkit().beep();
    }
  }
  public int checkInput(String proposedValue) throws NumberFormatException {
    int newValue = 0;
    if (proposedValue.length() > 0) {
      newValue = Integer.parseInt(proposedValue);
    }
    if ((minimum <= newValue) && (newValue <= maximum)) {
      return newValue;
    } else {
      throw new NumberFormatException();
    }
  }
}





Validate a value on the lostFocus event

    
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Main {
  JTextField tf1;
  public void init() {
    tf1 = new JTextField(5);
 
    tf1.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
      };
      public void focusLost(FocusEvent e) {
        if (!e.isTemporary()) {
          String content = tf1.getText();
          if (!content.equals("a") ) {
            System.out.println("illegal value! " + content);
            SwingUtilities.invokeLater(new FocusGrabber(tf1));
          }
        }
      }
    });
  }
}
class FocusGrabber implements Runnable {
  private JComponent component;
  public FocusGrabber(JComponent component) {
    this.ruponent = component;
  }
  public void run() {
    component.grabFocus();
  }
}





Water mark text field

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class WatermarkTextField extends JTextField {
  BufferedImage img;
  TexturePaint texture;
  public WatermarkTextField(File file)  {
    super();
    try {
      img = ImageIO.read(file);
    } catch (IOException e) {
      e.printStackTrace();
    }
    Rectangle rect = new Rectangle(0, 0, img.getWidth(null), img.getHeight(null));
    texture = new TexturePaint(img, rect);
    setOpaque(false);
  }
  public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(texture);
    g.fillRect(0, 0, getWidth(), getHeight());
    super.paintComponent(g);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JTextField textfield = new WatermarkTextField(new File("waterMarkImage.png"));
    textfield.setText("www.jexp.ru");
    frame.getContentPane().add(textfield);
    frame.pack();
    frame.setVisible(true);
  }
}