CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Swing

Swing
Labels and text fields
Labels

Two versions of a panel that displays two text fields

Common constructors of the JTextField class

Constructor Description
JTextField(intColumns) Creates a text field with the specified number of columns.
JTextField(String, intColumns) Creates a text field that starts with the text specified by the string and contains the specified number of columns.

Common methods of the JTextField class

Method Description
getText() Returns the text in this text field as a String object.
setText(String) Sets the text in this field to the specified string.
setColumns(intSize) Sets the number of columns to the specified value.
setEditable(boolean) Determines whether or not the field can be edited.
setFocusable(boolean) Determines whether or not the field can receive the focus.

A class that creates the panel with two text fields

class TextFieldPanel extends JPanel
{
    private JTextField textFieldOne, textFieldTwo;

    public TextFieldPanel()
    {
        textFieldOne = new JTextField("Test", 20);
        this.add(textFieldOne);
        textFieldTwo = new JTextField(10);
        this.add(textFieldTwo);
    }
}

Code that modifies the second text field

public void modifyFields()
{
    String data = textFieldOne.getText();
    textFieldTwo.setText(data);
    textFieldTwo.setColumns(20);
    textFieldTwo.setEditable(false);
}

Previous | Labels | Text fields | Next