Java记事本添加保存功能
时间: 2023-12-14 07:40:01 浏览: 52
要添加保存功能,你需要按以下步骤进行操作:
1. 在JFrame中添加一个“保存”按钮。
2. 添加ActionListener来处理按钮点击事件。
3. 在事件处理程序中,使用JFileChooser选择要保存的文件。
4. 通过FileWriter写入文本内容到选择的文件中。
下面是一个简单的示例代码,可以帮助你快速实现保存功能:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class NotePad extends JFrame {
private JTextArea textArea;
public NotePad() {
initUI();
}
private void initUI() {
setTitle("Java记事本");
setSize(500, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JButton saveButton = new JButton("保存");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(NotePad.this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileWriter writer = new FileWriter(file);
writer.write(textArea.getText());
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(saveButton);
Container contentPane = getContentPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
NotePad notePad = new NotePad();
notePad.setVisible(true);
});
}
}
```
在这个示例代码中,我们创建了一个JFrame,添加了一个JTextArea和一个“保存”按钮。当用户单击“保存”按钮时,我们使用JFileChooser选择要保存的文件,并将文本内容写入文件中。
你可以根据自己的需要进行调整,比如添加打开、新建、另存为等功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)