Java Tutorial/Swing/JTextField — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:32, 31 мая 2010
Содержание
- 1 Adding ActionListener to JTextField
- 2 Add key listener event handler to JTextField
- 3 Aligning the Text in a JTextField Component
- 4 Apply special filter to a JTextField
- 5 Based on JTextField content, enable or disable a JButton
- 6 Customizing a JTextField Look and Feel
- 7 Cut, paste, and copy in a JTextField
- 8 Drag and drop Text Demo
- 9 extends JTextField to create integer JTextField
- 10 Format JTextField"s text to uppercase
- 11 HighLight painter and JTextField
- 12 Horizontal Alignment
- 13 JTextField with a JScrollBar for Scrolling
- 14 Limit JTextField input to a maximum length
- 15 Make a Text Field two columns wide
- 16 Right justified JTextfield content
- 17 Set the focus on a particular JTextField
- 18 Sharing Data Models between two JTextField
- 19 Subclass InputVerfier
- 20 To make sure that the end of the contents is visible
- 21 Use the write() method to write the contents
- 22 Using Actions with Text Components: JTextField
- 23 Using JLabel Mnemonics: Interconnect a specific JLabel and JTextField
- 24 Verifying Input During Focus Traversal
Adding ActionListener to JTextField
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class AddingActionListenerJTextField {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField jTextField1 = new JTextField();
jTextField1.setText("jTextField1");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("action");
}
});
frame.add(jTextField1);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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);
}
}
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);
}
}
Apply special filter to a JTextField
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 JTextFieldFilter extends PlainDocument {
public static final String NUMERIC = "0123456789";
protected String acceptedChars = null;
protected boolean negativeAccepted = false;
public JTextFieldFilter() {
this(NUMERIC);
}
public JTextFieldFilter(String acceptedchars) {
acceptedChars = acceptedchars;
}
public void setNegativeAccepted(boolean negativeaccepted) {
if (acceptedChars.equals(NUMERIC)) {
negativeAccepted = negativeaccepted;
acceptedChars += "-";
}
}
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null)
return;
for (int i = 0; i < str.length(); i++) {
if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == -1)
return;
}
if (negativeAccepted && str.indexOf("-") != -1) {
if (str.indexOf("-") != 0 || offset != 0) {
return;
}
}
super.insertString(offset, str, attr);
}
}
public class Main extends JFrame{
public static void main(String[] argv) throws Exception {
new Main();
}
public Main() {
JTextField tf1, tf1b, tf1c, tf2, tf3;
JLabel l1, l1b, l1c, l2, l3;
setLayout(new FlowLayout());
//
l1 = new JLabel("only numerics");
tf1 = new JTextField(10);
getContentPane().add(l1);
getContentPane().add(tf1);
tf1.setDocument(new JTextFieldFilter(JTextFieldFilter.NUMERIC));
setSize(300,300);
setVisible(true);
}
}
Based on JTextField content, enable or disable a JButton
import java.awt.BorderLayout;
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.Document;
public class Main {
public Main() {
JButton button = new JButton("foo");
JTextField textField = new JTextField(10);
Document document = textField.getDocument();
document.addDocumentListener(new JButtonStateController(button));
JFrame frame = new JFrame();
frame.add(button,BorderLayout.WEST);
frame.add(textField,BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class JButtonStateController implements DocumentListener {
JButton button;
JButtonStateController(JButton button) {
this.button = button ;
}
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);
}
}
Customizing a JTextField Look and Feel
Property StringObject TypetextColortextHighlightColortextHighlightTextColortextInactiveTextColorTextField.actionMapActionMapTextField.backgroundColorTextField.borderBorderTextField.caretAspectRatioNumberTextField.caretBlinkRateIntegerTextField.caretForegroundColorTextField.darkShadowColorTextField.disabledBackgroundColorTextField.focusInputMapInputMapTextField.fontFontTextField.foregroundColorTextField.highlightColorTextField.inactiveBackgroundColorTextField.inactiveForegroundColorTextField.keyBindingsKeyBinding[ ]TextField.lightColorTextField.marginInsetsTextField.selectionBackgroundColorTextField.selectionForegroundColorTextField.shadowColorTextFieldUIString
Cut, paste, and copy in a JTextField
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 {
public static void main(String args[]) {
final JTextField textField = new JTextField(15);
JButton buttonCut = new JButton("Cut");
JButton buttonPaste = new JButton("Paste");
JButton buttonCopy = new JButton("Copy");
JFrame jfrm = new JFrame("Cut, Copy, and Paste");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(230, 150);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonCut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.cut();
}
});
buttonPaste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.paste();
}
});
buttonCopy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
textField.copy();
}
});
textField.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
System.out.println("All text: " + textField.getText());
if (textField.getSelectedText() != null)
System.out.println("Selected text: " + textField.getSelectedText());
else
System.out.println("Selected text: ");
}
});
jfrm.add(textField);
jfrm.add(buttonCut);
jfrm.add(buttonPaste);
jfrm.add(buttonCopy);
jfrm.setVisible(true);
}
}
Drag and drop Text Demo
import java.awt.Container;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class DragDropText extends JFrame {
public static void main(String[] args) {
new DragDropText().setVisible(true);
}
public DragDropText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField field1 = new JTextField("Life"s a drag", 20);
JTextField field2 = new JTextField("and then you drop", 20);
field1.setDragEnabled(true);
field2.setDragEnabled(true);
Container content = getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(field1);
content.add(field2);
pack();
}
}
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();
}
}
}
}
}
Format JTextField"s text to uppercase
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class Main extends JFrame {
public Main() throws HeadlessException {
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
DocumentFilter filter = new UppercaseDocumentFilter();
JTextField firstName = new JTextField();
firstName.setPreferredSize(new Dimension(100, 20));
((AbstractDocument) firstName.getDocument()).setDocumentFilter(filter);
JTextField lastName = new JTextField();
lastName.setPreferredSize(new Dimension(100, 20));
((AbstractDocument) lastName.getDocument()).setDocumentFilter(filter);
add(firstName);
add(lastName);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
class UppercaseDocumentFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
fb.insertString(offset, text.toUpperCase(), attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}
HighLight painter and JTextField
/*
* Copyright (c) 1995 - 2008 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:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - 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.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*/
/*
* TextFieldDemo.java requires one additional file:
* content.txt
*/
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.GroupLayout;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class TextFieldDemo extends JFrame implements DocumentListener {
private JTextField entry;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
private JLabel status;
private JTextArea textArea;
final static Color HILIT_COLOR = Color.LIGHT_GRAY;
final static Color ERROR_COLOR = Color.PINK;
final static String CANCEL_ACTION = "cancel-search";
final Color entryBg;
final Highlighter hilit;
final Highlighter.HighlightPainter painter;
public TextFieldDemo() {
initComponents();
InputStream in = getClass().getResourceAsStream("content.txt");
try {
textArea.read(new InputStreamReader(in), null);
} catch (IOException e) {
e.printStackTrace();
}
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
textArea.setHighlighter(hilit);
entryBg = entry.getBackground();
entry.getDocument().addDocumentListener(this);
InputMap im = entry.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = entry.getActionMap();
im.put(KeyStroke.getKeyStroke("ESCAPE"), CANCEL_ACTION);
am.put(CANCEL_ACTION, new CancelAction());
}
/**
* This method is called from within the constructor to initialize the form.
*/
private void initComponents() {
entry = new JTextField();
textArea = new JTextArea();
status = new JLabel();
jLabel1 = new JLabel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("TextFieldDemo");
textArea.setColumns(20);
textArea.setLineWrap(true);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
jScrollPane1 = new JScrollPane(textArea);
jLabel1.setText("Enter text to search:");
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
// Create a parallel group for the horizontal axis
ParallelGroup hGroup = layout
.createParallelGroup(GroupLayout.Alignment.LEADING);
// Create a sequential and a parallel groups
SequentialGroup h1 = layout.createSequentialGroup();
ParallelGroup h2 = layout
.createParallelGroup(GroupLayout.Alignment.TRAILING);
// Add a container gap to the sequential group h1
h1.addContainerGap();
// Add a scroll pane and a label to the parallel group h2
h2.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING,
GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
h2.addComponent(status, GroupLayout.Alignment.LEADING,
GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE);
// Create a sequential group h3
SequentialGroup h3 = layout.createSequentialGroup();
h3.addComponent(jLabel1);
h3.addPreferredGap(LayoutStyle.ruponentPlacement.RELATED);
h3.addComponent(entry, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE);
// Add the group h3 to the group h2
h2.addGroup(h3);
// Add the group h2 to the group h1
h1.addGroup(h2);
h1.addContainerGap();
// Add the group h1 to the hGroup
hGroup.addGroup(GroupLayout.Alignment.TRAILING, h1);
// Create the horizontal group
layout.setHorizontalGroup(hGroup);
// Create a parallel group for the vertical axis
ParallelGroup vGroup = layout
.createParallelGroup(GroupLayout.Alignment.LEADING);
// Create a sequential group v1
SequentialGroup v1 = layout.createSequentialGroup();
// Add a container gap to the sequential group v1
v1.addContainerGap();
// Create a parallel group v2
ParallelGroup v2 = layout
.createParallelGroup(GroupLayout.Alignment.BASELINE);
v2.addComponent(jLabel1);
v2.addComponent(entry, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE);
// Add the group v2 tp the group v1
v1.addGroup(v2);
v1.addPreferredGap(javax.swing.LayoutStyle.ruponentPlacement.RELATED);
v1.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 233,
Short.MAX_VALUE);
v1.addPreferredGap(javax.swing.LayoutStyle.ruponentPlacement.RELATED);
v1.addComponent(status);
v1.addContainerGap();
// Add the group v1 to the group vGroup
vGroup.addGroup(v1);
// Create the vertical group
layout.setVerticalGroup(vGroup);
pack();
}
public void search() {
hilit.removeAllHighlights();
String s = entry.getText();
if (s.length() <= 0) {
message("Nothing to search");
return;
}
String content = textArea.getText();
int index = content.indexOf(s, 0);
if (index >= 0) { // match found
try {
int end = index + s.length();
hilit.addHighlight(index, end, painter);
textArea.setCaretPosition(end);
entry.setBackground(entryBg);
message(""" + s + "" found. Press ESC to end search");
} catch (BadLocationException e) {
e.printStackTrace();
}
} else {
entry.setBackground(ERROR_COLOR);
message(""" + s + "" not found. Press ESC to start a new search");
}
}
void message(String msg) {
status.setText(msg);
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
search();
}
public void removeUpdate(DocumentEvent ev) {
search();
}
public void changedUpdate(DocumentEvent ev) {
}
class CancelAction extends AbstractAction {
public void actionPerformed(ActionEvent ev) {
hilit.removeAllHighlights();
entry.setText("");
entry.setBackground(entryBg);
}
}
public static void main(String args[]) {
// Schedule a job for the event dispatch thread:
// creating and showing this application"s GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Turn off metal"s use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
new TextFieldDemo().setVisible(true);
}
});
}
}
Horizontal Alignment
By default, the text alignment is left-justified.
public void setHorizontalAlignment(int alignment) method takes an argument of
- JTextField.LEFT,
- JTextField.CENTER,
- JTextField.RIGHT,
- JTextField.LEADING (the default), or
- JTextField.TRAILING.
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LabelSampleHorizontalAlignment {
public static void main(String args[]) {
JFrame frame = new JFrame("Label Focus Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Name: ");
label.setDisplayedMnemonic(KeyEvent.VK_N);
JTextField textField = new JTextField();
textField.setHorizontalAlignment(JTextField.CENTER) ;
label.setLabelFor(textField);
panel.add(label, BorderLayout.WEST);
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
JTextField with a JScrollBar for Scrolling
Built inside the JTextField is a scrollable area used when the width of the component"s contents exceeds its visible horizontal space.
A BoundedRangeModel controls this scrolling area.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoundedRangeModel;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
public class TextSlider {
public static void main(String args[]) {
JFrame frame = new JFrame("Text Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField textField = new JTextField();
JScrollBar scrollBar = new JScrollBar(JScrollBar.HORIZONTAL);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
BoundedRangeModel brm = textField.getHorizontalVisibility();
scrollBar.setModel(brm);
panel.add(textField);
panel.add(scrollBar);
final TextSlider ts = new TextSlider();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Text: " + textField.getText());
}
});
frame.add(panel, BorderLayout.NORTH);
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();
}
}
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);
}
}
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();
}
});
}
}
Sharing Data Models between two JTextField
The JTextField component is the text component for a single line of input.
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.Document;
public class ShareModel {
public static void main(String args[]) {
JFrame frame = new JFrame("Sharing Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textarea1 = new JTextArea();
Document document = textarea1.getDocument();
JTextArea textarea2 = new JTextArea(document);
JTextArea textarea3 = new JTextArea(document);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.add(new JScrollPane(textarea1));
frame.add(new JScrollPane(textarea2));
frame.add(new JScrollPane(textarea3));
frame.setSize(300, 400);
frame.setVisible(true);
}
}
Subclass InputVerfier
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
public class Main {
public static void main(String[] args) {
JTextField tf = new JTextField("");
tf.setInputVerifier(new MyInputVerifier());
}
}
class MyInputVerifier extends InputVerifier {
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
String pass = tf.getText();
return pass.equals("A");
}
}
To make sure that the end of the contents is visible
By changing the scrollOffset setting, you can control which part of the text field is visible.
To make sure that the end of the contents is visible, you need to ask the horizontalVisibility property what the extent of the BoundedRangeModel is, to determine the width of the range, and then set the scrollOffset setting to the extent setting, as follows:
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LabelSampleBoundedRangeModel {
public static void main(String args[]) {
JFrame frame = new JFrame("Label Focus Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Name: ");
label.setDisplayedMnemonic(KeyEvent.VK_N);
JTextField textField = new JTextField();
label.setLabelFor(textField);
panel.add(label, BorderLayout.WEST);
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(250, 150);
frame.setVisible(true);
textField.setText("Loooooooooooooooooooooooooooooooooooooooooooooooooooooooong");
BoundedRangeModel model = textField.getHorizontalVisibility();
int extent = model.getExtent();
textField.setScrollOffset(extent);
System.out.println("extent:"+extent);
}
}
Use the write() method to write the contents
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LabelSampleSaveText {
public static void main(String args[]) {
JFrame frame = new JFrame("Label Focus Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Name: ");
label.setDisplayedMnemonic(KeyEvent.VK_N);
JTextField textField = new JTextField();
label.setLabelFor(textField);
panel.add(label, BorderLayout.WEST);
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
textField.setText("your text");
String filename = "test.txt";
FileWriter writer = null;
try {
writer = new FileWriter(filename);
textField.write(writer);
} catch (IOException exception) {
System.err.println("Save oops");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException exception) {
System.err.println("Error closing writer");
exception.printStackTrace();
}
}
}
}
}
Using Actions with Text Components: JTextField
import java.util.Arrays;
import java.util.ruparator;
import javax.swing.Action;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class ListActionsJTextField {
public static void main(String args[]) {
JTextComponent component = new JTextField();
// Process action list
Action actions[] = component.getActions();
// Define comparator to sort actions
Comparator<Action> comparator = new Comparator<Action>() {
public int compare(Action a1, Action a2) {
String firstName = (String) a1.getValue(Action.NAME);
String secondName = (String) a2.getValue(Action.NAME);
return firstName.rupareTo(secondName);
}
};
Arrays.sort(actions, comparator);
int count = actions.length;
System.out.println("Count: " + count);
for (int i = 0; i < count; i++) {
System.out.printf("%28s : %s\n",actions[i].getValue(Action.NAME),actions[i].getClass().getName());
}
}
}
Count: 54 beep : javax.swing.text.DefaultEditorKit$BeepAction caret-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-begin : javax.swing.text.DefaultEditorKit$BeginAction caret-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction caret-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction caret-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction caret-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-end : javax.swing.text.DefaultEditorKit$EndAction caret-end-line : javax.swing.text.DefaultEditorKit$EndLineAction caret-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction caret-end-word : javax.swing.text.DefaultEditorKit$EndWordAction caret-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-next-word : javax.swing.text.DefaultEditorKit$NextWordAction caret-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction caret-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction copy-to-clipboard : javax.swing.text.DefaultEditorKit$CopyAction cut-to-clipboard : javax.swing.text.DefaultEditorKit$CutAction default-typed : javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction delete-next : javax.swing.text.DefaultEditorKit$DeleteNextCharAction delete-previous : javax.swing.text.DefaultEditorKit$DeletePrevCharAction dump-model : javax.swing.text.DefaultEditorKit$DumpModelAction insert-break : javax.swing.text.DefaultEditorKit$InsertBreakAction insert-content : javax.swing.text.DefaultEditorKit$InsertContentAction insert-tab : javax.swing.text.DefaultEditorKit$InsertTabAction notify-field-accept : javax.swing.JTextField$NotifyAction page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction paste-from-clipboard : javax.swing.text.DefaultEditorKit$PasteAction select-all : javax.swing.text.DefaultEditorKit$SelectAllAction select-line : javax.swing.text.DefaultEditorKit$SelectLineAction select-paragraph : javax.swing.text.DefaultEditorKit$SelectParagraphAction select-word : javax.swing.text.DefaultEditorKit$SelectWordAction selection-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-begin : javax.swing.text.DefaultEditorKit$BeginAction selection-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction selection-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction selection-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction selection-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-end : javax.swing.text.DefaultEditorKit$EndAction selection-end-line : javax.swing.text.DefaultEditorKit$EndLineAction selection-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction selection-end-word : javax.swing.text.DefaultEditorKit$EndWordAction selection-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-next-word : javax.swing.text.DefaultEditorKit$NextWordAction selection-page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-page-left : javax.swing.text.DefaultEditorKit$PageAction selection-page-right : javax.swing.text.DefaultEditorKit$PageAction selection-page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction selection-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction set-read-only : javax.swing.text.DefaultEditorKit$ReadOnlyAction set-writable : javax.swing.text.DefaultEditorKit$WritableAction toggle-componentOrientation : javax.swing.text.DefaultEditorKit$ToggleComponentOrientationAction unselect : javax.swing.text.DefaultEditorKit$UnselectAction
Using JLabel Mnemonics: Interconnect a specific JLabel and JTextField
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LabelSampleLabelFor {
public static void main(String args[]) {
JFrame frame = new JFrame("Label Focus Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Name: ");
label.setDisplayedMnemonic(KeyEvent.VK_N);
JTextField textField = new JTextField();
label.setLabelFor(textField);
panel.add(label, BorderLayout.WEST);
panel.add(textField, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
frame.setSize(250, 150);
frame.setVisible(true);
}
}
Verifying Input During Focus Traversal
import java.awt.BorderLayout;
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();
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);
frame.add(textField1, BorderLayout.NORTH);
frame.add(textField2, BorderLayout.CENTER);
frame.setSize(300, 100);
frame.setVisible(true);
}
}