java弹出窗放textarea_怎么让文件的内容在textArea中显示出来?
时间: 2024-02-25 08:58:04 浏览: 71
可以使用以下代码实现在Java Swing中弹出窗口并在TextArea中显示文件内容的功能:
```java
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FileViewer extends JFrame implements ActionListener {
private JButton openButton;
private JTextArea textArea;
public FileViewer() {
super("File Viewer");
// Create components
openButton = new JButton("Open");
openButton.addActionListener(this);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
// Add components to content pane
Container contentPane = getContentPane();
contentPane.add(openButton, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
// Set window properties
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// Create and show window
FileViewer fileViewer = new FileViewer();
fileViewer.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
// Create file chooser dialog
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
// Get selected file
File file = fileChooser.getSelectedFile();
try {
// Read file contents
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
reader.close();
// Set text area contents
textArea.setText(sb.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
```
这段代码会创建一个名为 "File Viewer" 的窗口,其中包含一个 "Open" 按钮和一个文本区域。当用户点击 "Open" 按钮时,会弹出一个文件选择器对话框,用户可以选择要读取的文件。然后,程序会读取文件内容并将其显示在文本区域中。
阅读全文