import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class TextAreaTest extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextArea ta;
private JButton print, clear, exit, save, load;
public TextAreaTest(int rows, int cols) {
setLayout(new BorderLayout());
ta = new JTextArea(10, 40);
add(ta, BorderLayout.CENTER);
JPanel south = new JPanel();
south.setLayout(new GridLayout(1, 3));
print = new JButton("Print");
south.add(print);
print.addActionListener(this);
clear = new JButton("Clear");
south.add(clear);
clear.addActionListener(this);
exit = new JButton("Exit");
south.add(exit);
exit.addActionListener(this);
save = new JButton("Save");
south.add(save);
save.addActionListener(this);
load = new JButton("Load");
south.add(load);
load.addActionListener(this);
add(south, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exit)
System.exit(0);
if (e.getSource() == print)
System.out.println(ta.getText());
if (e.getSource() == clear) {
ta.setText("");
ta.repaint();
}
if (e.getSource() == save)
try {
File ausgabeDatei = new File("c:\\test.txt");
FileWriter fw = new FileWriter(ausgabeDatei);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(ta.getText());
bw.newLine();
bw.close();
fw.close();
}
catch (Exception a) {
JOptionPane.showMessageDialog(null, "Fehler beim Speichern der Datei.", "Fehler", JOptionPane.ERROR_MESSAGE);
a.printStackTrace();
}
if (e.getSource() == load) {
System.out.println("load");
try {
BufferedReader reader = new BufferedReader(new FileReader("d:\\test.txt"));
String line;
while ((line = reader.readLine()) != null) {
ta.append(line + "\n");
}
reader.close();
}
catch (Exception a) {
JOptionPane.showMessageDialog(null, "Fehler beim Speichern der Datei. (Datei nicht gefunden)", "Fehler", JOptionPane.ERROR_MESSAGE);
a.printStackTrace();
}
}
}
public static void main(String[] args) {
new TextAreaTest(2, 1).setVisible(true);
}
}