请用Java是实现GUI示例代码,作用如下:让用户在输入一个文件名,然后单击open键可显示文件内容,文件内容以二进制形式显示在文本框内。用户可修改文件内容,单击save键可保存,然后将修改后的内容回存到这个文件中,当退出程序时,若文件修改后未点击save进行保存,则需提醒用户是否保存
时间: 2023-02-06 15:39:29 浏览: 111
以下是使用 Java 实现 GUI 的示例代码:
```
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class FileViewer extends JFrame implements ActionListener {
private JTextField fileNameField;
private JTextArea fileContentArea;
private JButton openButton;
private JButton saveButton;
private File currentFile;
public FileViewer() {
// 创建文件名输入框和按钮
fileNameField = new JTextField(20);
openButton = new JButton("Open");
openButton.addActionListener(this);
// 创建文件内容显示区域和按钮
fileContentArea = new JTextArea(20, 40);
saveButton = new JButton("Save");
saveButton.addActionListener(this);
// 创建面板并添加组件
JPanel panel = new JPanel();
panel.add(new JLabel("Enter file name:"));
panel.add(fileNameField);
panel.add(openButton);
panel.add(saveButton);
// 设置窗口布局
setLayout(new BorderLayout());
add(panel, BorderLayout.NORTH);
add(new JScrollPane(fileContentArea), BorderLayout.CENTER);
// 设置窗口属性
setTitle("File Viewer");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (currentFile != null && fileContentArea.getText().equals(readFile(currentFile))) {
dispose();
System.exit(0);
} else {
int confirm = JOptionPane.showConfirmDialog(
FileViewer.this, "Do you want to save the changes?", "Confirm",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
saveFile();
} else if (confirm == JOptionPane.NO_OPTION) {
dispose();
System.exit(0);
}
}
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// 读取文件内容
private String readFile(File file) {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
阅读全文