请用Java是实现GUI示例代码,作用如下:让用户在输入一个文件名,然后单击open键可显示文件内容,文件内容以二进制形式显示在文本框内。用户可修改文件内容,单击save键可保存,然后将修改后的内容回存到这个文件中,当退出程序时,若文件修改后未点击save进行保存,则需提醒用户是否保存,Y表示保存,N表示不保存,C表示取消退出
时间: 2023-02-06 20:05:18 浏览: 70
以下是使用 Java 实现 GUI 的示例代码:
```
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FileEditor extends JFrame {
private JTextField fileNameField;
private JTextArea fileContentArea;
private File currentFile;
private boolean fileChanged;
public FileEditor() {
// 创建 GUI 的各个组件
fileNameField = new JTextField(20);
fileContentArea = new JTextArea(20, 60);
JButton openButton = new JButton("Open");
JButton saveButton = new JButton("Save");
JButton exitButton = new JButton("Exit");
// 设置布局
setLayout(new BorderLayout());
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
topPanel.add(fileNameField);
topPanel.add(openButton);
topPanel.add(saveButton);
topPanel.add(exitButton);
add(topPanel, BorderLayout.NORTH);
add(fileContentArea, BorderLayout.CENTER);
// 为按钮添加监听器
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openFile();
}
});
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
});
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exit();
}
});
}
// 打开文件
private void openFile() {
String fileName = fileNameField.getText();
if (fileName.isEmpty()) {
JOptionPane.showMessageDialog(this, "请输入文件名", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
currentFile = new File(fileName);
if (!currentFile.exists()) {
JOptionPane.showMessageDialog(this, "文件不存在", "错误", JOptionPane.ERROR_MESSAGE);
return;
}