请编写一个Java程序实现如下图所示的“文本文件阅读器”窗体(TextFileViewer): 窗体的主要区域是一个JTextArea对象,放置在一个JScrollPane中。窗体底部由三个组件构成,分别是标签、文本框(设置为只读,即不可编辑)和一个按钮。 请注意各个组件的布局关系并合理使用布局管理器。
时间: 2024-03-25 14:37:25 浏览: 68
以下是实现文本文件阅读器窗体的Java程序:
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class TextFileViewer extends JFrame implements ActionListener {
private JTextArea textArea;
private JTextField filePathField;
private JLabel statusLabel;
public TextFileViewer() {
super("文本文件阅读器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(800, 600));
// 创建文本区域并放置在滚动面板中
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
// 创建底部面板
JPanel bottomPanel = new JPanel(new BorderLayout());
// 创建底部标签
JLabel filePathLabel = new JLabel("文件路径:");
// 创建底部文本框
filePathField = new JTextField();
filePathField.setEditable(false);
// 创建底部按钮
JButton openButton = new JButton("打开文件");
openButton.addActionListener(this);
// 创建底部状态标签
statusLabel = new JLabel("就绪");
// 将底部组件添加到底部面板中
bottomPanel.add(filePathLabel, BorderLayout.WEST);
bottomPanel.add(filePathField, BorderLayout.CENTER);
bottomPanel.add(openButton, BorderLayout.EAST);
bottomPanel.add(statusLabel, BorderLayout.SOUTH);
// 将滚动面板和底部面板添加到窗体中
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("打开文件")) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
filePathField.setText(file.getAbsolutePath());
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
textArea.read(reader, null);
statusLabel.setText("已打开文件:" + file.getName());
} catch (IOException ex) {
ex.printStackTrace();
statusLabel.setText("打开文件失败:" + ex.getMessage());
}
}
}
}
public static void main(String[] args) {
new TextFileViewer();
}
}
```
上面的程序使用了Java Swing组件库,实现了一个简单的文本文件阅读器窗体。程序中使用了JFileChooser组件选择文件,使用JTextArea组件显示文件内容,使用JScrollPane组件包装JTextArea以实现滚动功能,使用JTextField组件显示文件路径,使用JButton组件打开文件,使用JLabel组件显示状态信息。程序中还实现了ActionListener接口,处理打开文件按钮的点击事件。
阅读全文
相关推荐


















