import java.awt.*;
import java.io.*;
public class FileToTextArea extends JFrame {
private JTextArea textArea;
public FileToTextArea() {
setTitle("File to TextArea");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JButton openButton = new JButton("Open File");
openButton.addActionListener(e -> openFile());
add(openButton, BorderLayout.SOUTH);
setVisible(true);
}
private void openFile() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
textArea.setText(""); // Clear existing text
String line;
while ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Error reading file: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(FileToTextArea::new);
}
}
No comments:
Post a Comment