This example shows you how to create a simple JTextArea
component in Java Swing application. First you’ll create an instance of JTextAread
and passes the number of rows and columns. Next to add a scroll ability you can wrap the component inside a JScrollPane
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaDemo extends JPanel {
public TextAreaDemo() {
initializeUI();
}
public static void showFrame() {
JPanel panel = new TextAreaDemo();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TextAreaDemo::showFrame);
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
// Creates a JTextArea with 5 rows and 40 columns. Then
// wrap the JTextArea inside a JScrollPane for adding
// scrolling abilities.
JTextArea textArea = new JTextArea(5, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
}
}
The result of our code snippet is:
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023