Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add Text Area to a Frame using Swing API in Java ?

Program to demonstrate adding of Text Area to a Frame.

package com.hubberspot.swing.example;

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.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaDemo extends JFrame {
  private JButton add = new JButton("Add Data");
  private JButton clear = new JButton("Clear Data");
  private JTextArea textarea = new JTextArea(2, 25);

  public TextAreaDemo() {
    add.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
 textarea.setText("Welcome to Hubberspot.com!");
      }
    });

    clear.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
 textarea.setText("");
      }
    });
    setLayout(new FlowLayout());
    add(new JScrollPane(textarea));
    add(add);
    add(clear);
  }

  public static void main(String[] args) {
    setFrame(new TextAreaDemo(), 300, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
 frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
       }
     });
   }

} 

Output of the program :



















 
© 2021 Learn Java by Examples Template by Hubberspot