Using the read(Reader in, Object desc)
method inherited from the JTextComponent
allow us to populate a JTextArea
with text content from a file. This example will show you how to do it.
In this example we use an InputStreamReader
to read a file from our application resource. You could use other Reader
implementation such as the FileReader
to read the content of a file. Let’s see the code below.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;
public class PopulateTextAreaFromFile extends JPanel {
public PopulateTextAreaFromFile() {
initialize();
}
public static void showFrame() {
JPanel panel = new PopulateTextAreaFromFile();
panel.setOpaque(true);
JFrame frame = new JFrame("Populate JTextArea from File");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(PopulateTextAreaFromFile::showFrame);
}
private void initialize() {
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
try {
// Read some text from the resource file to display in
// the JTextArea.
textArea.read(new InputStreamReader(Objects.requireNonNull(
getClass().getResourceAsStream("/data.txt"))), null);
} catch (IOException e) {
e.printStackTrace();
}
this.setPreferredSize(new Dimension(500, 200));
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
}
The output of the code snippet above is:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024