我开始学习 Java,但不知道如何在 JTextField 中显示由 JFileChooser 打开的给定文件的内容
这是我到目前为止的代码。
为了更好地理解我的程序,我删除了一些导入和代码。
public class Afvink6 extends JFrame implements ActionListener {
private JLabel bestandnaam;
private JTextField bestand;
private JButton blader;
private JButton analyseer;
private JLabel informatie;
private JTextArea textarea;
private JLabel naampercentage;
private JPanel percentages;
private PrintWriter outFile;
private JFileChooser fileChooser;
private int reply;
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == blader){
fileChooser = new JFileChooser();
reply = fileChooser.showOpenDialog(this);
if (reply == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
bestand.setText(selectedFile.getAbsolutePath());
}
}
if(event.getSource() ==analyseer){
希望有人能帮助我!
最佳答案
File.getAbsolutePath() 仅返回路径名。您需要将 setText 设置为文件的实际内容。
您可以通过多种方式做到这一点。这是其中之一:
java.nio.file.Files.readAllLines(selectedFile.toPath(), Charset.defaultCharset());
例如,将返回一个列表,您可以将其全部连接在一起并在 JTextField 上设置Text以显示所有内容。
建议:您可能想使用 TextArea (显示多行)。请参阅:Loading a text file into a text area
关于Java:如何在 JTextField 中显示由 JFileChooser 打开的文件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040720/