What are the differences between JTextField and JTextArea in Java?


The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

JTextField

  • A JTextFeld is one of the most important components that allow the user to an input text value in a single line format.
  • A JTextField will generate an ActionListener interface when we trying to enter some input inside it.
  • The JTextComponent is a superclass of JTextField that provides a common set of methods used by JTextfield.
  • The important methods in the JTextField class are setText(), getText(), setEnabled(), etc.

Example

import javax.swing.*;
import java.awt.*;
public class JTextFieldTest {
   public static void main(String[] args) {
      final JFrame frame = new JFrame("JTextField Demo");    
      JLabel lblFirstName = new JLabel("First Name:");
      JTextField tfFirstName = new JTextField(20);
      lblFirstName.setLabelFor(tfFirstName);
      JLabel lblLastName = new JLabel("Last Name:");
      JTextField tfLastName = new JTextField(20);
      lblLastName.setLabelFor(tfLastName);
      JPanel panel = new JPanel();
      panel.setLayout(new FlowLayout());
      panel.add(lblFirstName);
      panel.add(tfFirstName);
      panel.add(lblLastName);
      panel.add(tfLastName);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(300, 100);
      frame.getContentPane().add(panel, BorderLayout.CENTER);
      frame.setVisible(true);
   }
}

Output

JTextArea

  • A JTextArea is a multi-line text component to display text or allow the user to enter text.
  • A JTextArea will generate a CaretListener interface.
  • The JTextComponent is a superclass of JTextArea that provides a common set of methods used by JTextArea.
  • The important methods in the JTextArea class are setText(), append(), setLineWrap(), setWrapStyleWord(), setCaretPosition(), etc.

Example

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class JTextAreaTest {
   public static void main(String args[]) {
      JFrame frame = new JFrame("JTextArea Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JTextArea textArea = new JTextArea();
      JScrollPane scrollPane = new JScrollPane(textArea);
      frame.add(scrollPane, BorderLayout.CENTER);
      CaretListener listener = new CaretListener() {
         public void caretUpdate(CaretEvent caretEvent) {
            System.out.println("Dot: "+ caretEvent.getDot());
            System.out.println("Mark: "+caretEvent.getMark());
         }
      };
      textArea.addCaretListener(listener);
      frame.setSize(250, 150);
      frame.setVisible(true);
   }
}

Output

Updated on: 07-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements