Ниже приведен пример сохранения текстового файла с помощью JButton
для запуска события.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
public class DisplayPanel {
public static String textFilePath = // adjust path as needed
"C:\\Users\\Andrew\\Documents\\junk.txt";
private JComponent ui = null;
private JFrame frame;
private JTextArea theText;
private JButton saveButton;
private ActionListener actionListener;
File file;
DisplayPanel(File file) {
this.file = file;
try {
initUI();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void saveText() {
Writer writer = null;
try {
writer = new FileWriter(file);
theText.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public final void initUI() throws FileNotFoundException, IOException {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
theText = new JTextArea(20, 120); //120 monospaced chrs
theText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
theText.setLineWrap(true);
theText.setEditable(true);
JScrollPane scroll = new JScrollPane(theText);
scroll.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
ui.add(scroll);
saveButton = new JButton("Save");
ui.add(saveButton, BorderLayout.PAGE_START);
actionListener = (ActionEvent e) -> {
saveText();
};
saveButton.addActionListener(actionListener);
Reader reader = new FileReader(file);
theText.read(reader, file);
}
public void createAndShowGUI() {
frame = new JFrame(this.getClass().getSimpleName());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(getUI());
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
File file = new File(textFilePath);
DisplayPanel o = new DisplayPanel(file);
o.createAndShowGUI();
};
SwingUtilities.invokeLater(r);
}
}