Java JTextField set text and size

Description

Java JTextField set text and size


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Main extends JFrame {
  JTextField textField1; // text field with set size
  JTextField textField2; // text field with text
  JTextField textField3; // text field with text and size

  public Main() {
    super("Testing");
    setLayout(new FlowLayout());

    // construct textfield with 10 columns
    textField1 = new JTextField(10);
    add(textField1);/*w w w. j  a  v a  2 s . c o  m*/
    // construct textfield with default text
    textField2 = new JTextField("Enter text here");
    add(textField2);

    // construct textfield with default text and 21 columns
    textField3 = new JTextField("Uneditable text field", 21);
    textField3.setEditable(false); // disable editing
    add(textField3); 


    TextFieldHandler handler = new TextFieldHandler();
    textField1.addActionListener(handler);
    textField2.addActionListener(handler);
    textField3.addActionListener(handler);
  }

  private class TextFieldHandler implements ActionListener {
    // process textfield events
    @Override
    public void actionPerformed(ActionEvent event) {
      String string = "";
      // user pressed Enter in JTextField textField1
      if (event.getSource() == textField1)
        string = String.format("textField1: %s", event.getActionCommand());
      // user pressed Enter in JTextField textField2
      else if (event.getSource() == textField2)
        string = String.format("textField2: %s", event.getActionCommand());
      // user pressed Enter in JTextField textField3
      else if (event.getSource() == textField3)
        string = String.format("textField3: %s", event.getActionCommand());

      JOptionPane.showMessageDialog(null, string);
    }
  } 

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(350, 100);
    Main.setVisible(true);
  }
}



PreviousNext

Related