JTextField
Home ] Up ] JTextComponent ] [ JTextField ] JPasswordField ] JTextArea ] The Document Model ] JTextArea Scrolling ] JTextArea Editing ]

 

 

A JTextField is a text component that provides a single line of text.  

Here are some examples of how text fields can be used:

package swingExamples;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JTextField;

class SimpleTextFieldsPanel extends JPanel
{
  public SimpleTextFieldsPanel()
  {
    JTextField look = new JTextField();
    look.setText("Look at me!  I'm a text field!");
    add(look);
    JTextField whoopee = new JTextField(8); 
                           // 8 characters in current font
    whoopee.setText("Whoopee!");
    whoopee.setForeground(Color.RED);
    whoopee.setBackground(Color.BLUE);
    whoopee.setFont(new Font("monospaced", Font.BOLD, 18));
    add(whoopee);
    String text = 
        "Please quiet down up there; I'm trying to sleep...";
    JTextField conservative = new JTextField(text);
    conservative.setEditable(false);
    conservative.setFont(new Font("serif", Font.PLAIN, 10));
    add(conservative);
    JTextField bobby = 
        new JTextField("'ere, 'ere, Wot's going on 'ere?");
    bobby.setForeground(Color.YELLOW);
    bobby.setBackground(Color.BLACK);
    add(bobby);
  }
}

class SimpleTextFieldsFrame extends JFrame
{
  public SimpleTextFieldsFrame()
  {
    setTitle("SimpleTextFields");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    contentPane.add( new SimpleTextFieldsPanel() );
  }
}

public class SimpleTextFields
{
  public static void main(String[] args)
  {
    SimpleTextFieldsFrame frame = 
                    new SimpleTextFieldsFrame();
    frame.setVisible(true);
  }
}

which produces:

Notice that, when you set a text field as not editable, the default background color changes from white to light gray, and the border changes to make it look more 2-dimensional.

Both foreground and background colors may be set.

 

This page was last modified on 02 October, 2007