• How to use JTextArea in Java

    From our previous post, we learned how to use JLabel, JTextField and JPasswordField. In this post, we will concentrate on how to use JTextArea in Java. JTextArea is a component used so that users can type anything just like using a notepad. You can edit the fonts including the style and sizes and also html. Below is an example of a simple JTextArea.

    package com.javapointers.javase;
    
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    
    public class JTextAreaTest {
        
        JTextArea text;
        JFrame frame;
        
        public JTextAreaTest(){
            frame = new JFrame();
            text = new JTextArea(5,40);
            text.setLineWrap(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(text);
            frame.pack();
            frame.setTitle("JTextArea Test");
            frame.setVisible(true);
        }
        public static void main(String args[]){
            JTextAreaTest test = new JTextAreaTest();
        }
    }
    
    

    when we run our program, the UI will be like below:

    jtextarea example output

    Explanation:

    • text = new JTextArea(5,40);

    means to create a new instance of JTextArea with initial height of 5 and width of 40.

    • text.setLineWrap(true);

    we have set the line wrap to true so that when the cursor reaches the end of the area, it will automatically sets the cursor to the next line. Setting it to false will make the characters to be displayed in just one line and some text may not be displayed.

    That’s it on how to use JTextArea in Java applications. Next tutorial is about ActionListener which is being triggered or called whenever an action was made to a component.

    Related Post