-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTinyEdit.java
More file actions
64 lines (57 loc) · 2.38 KB
/
TinyEdit.java
File metadata and controls
64 lines (57 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class TinyEdit extends JFrame implements ActionListener {
private JTextArea textArea;
private JButton openButton, saveButton;
public TinyEdit() {
super("TinyEdit");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
openButton = new JButton("Open");
saveButton = new JButton("Save");
openButton.addActionListener(this);
saveButton.addActionListener(this);
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
textArea.read(reader, null);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "File could not be opened: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
} else if (e.getSource() == saveButton) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
textArea.write(writer);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "File could not be saved: " + ex.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TinyEdit::new);
}
}