用java图形界面的知识,编写一个软件,点击read按钮,读入指定txt文件中的内容,显示在左边文本域中,点击sort按钮,将文本域中以“dba”开头的字符串提取出来,放在右边的文本域中,点击save按钮,将处理后右边的文本保存到一个新的txt文档中
时间: 2024-03-03 17:48:48 浏览: 75
好的,这是一个比较完整的问题,我会尽可能详细地回答你。首先,我们需要使用Java的Swing库来创建图形界面,然后使用File类来读取和保存文件。下面是一个简单的实现:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MyApplication extends JFrame implements ActionListener {
private JTextArea leftTextArea;
private JTextArea rightTextArea;
public MyApplication() {
super("My Application");
// 创建界面
JPanel panel = new JPanel(new GridLayout(1, 3));
leftTextArea = new JTextArea();
rightTextArea = new JTextArea();
JButton readButton = new JButton("Read");
JButton sortButton = new JButton("Sort");
JButton saveButton = new JButton("Save");
panel.add(readButton);
panel.add(sortButton);
panel.add(saveButton);
getContentPane().add(panel, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(leftTextArea), BorderLayout.WEST);
getContentPane().add(new JScrollPane(rightTextArea), BorderLayout.EAST);
// 添加事件监听器
readButton.addActionListener(this);
sortButton.addActionListener(this);
saveButton.addActionListener(this);
// 设置窗口大小和可见性
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Read")) {
// 读取文件内容并显示在左边文本域中
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
leftTextArea.append(line + "\n");
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error reading file: " + ex.getMessage());
}
}
} else if (e.getActionCommand().equals("Sort")) {
// 提取以“dba”开头的字符串并显示在右边文本域中
String[] lines = leftTextArea.getText().split("\n");
rightTextArea.setText("");
for (String line : lines) {
if (line.startsWith("dba")) {
rightTextArea.append(line + "\n");
}
}
} else if (e.getActionCommand().equals("Save")) {
// 将右边文本域中的内容保存到新文件中
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(new FileWriter(file));
writer.print(rightTextArea.getText());
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage());
}
}
}
}
public static void main(String[] args) {
new MyApplication();
}
}
```
这个程序创建了一个包含三个按钮和两个文本域的窗口,点击“Read”按钮可以选择一个txt文件并将其内容显示在左边的文本域中,点击“Sort”按钮可以提取以“dba”开头的字符串并将其显示在右边的文本域中,点击“Save”按钮可以将右边文本域中的内容保存到一个新的txt文件中。
注意,在实际编写中,还需要添加一些错误处理和用户提示信息。
阅读全文
相关推荐














