2017-10-04 52 views
0

所以我一直在尝试做一个filechoos打开一个文本文件,然后将内容粘贴到我已经定义为textArea的JtextArea中。 但我无法让我的showOpenDialog在提供参数(this)时不给出错误,而且我研究了答案并填写(null),这确实使filechooser能够工作,但是当我尝试打印它的内容时它也只是返回null。我使用的是Eclipse程序,因此是自动填充的代码。 我对Java相当陌生,不知道怎么回事。 如果这不是在这里发布的东西的方式,我真的很抱歉。ShowopenDialog not working under actionlistener

JButton btnNewButton = new JButton("Bladeren"); 
btnNewButton.addActionListener(
    new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      JFileChooser fileChooser = new JFileChooser(); 
      fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); 
      int result = fileChooser.showOpenDialog(this); 
      if (result == JFileChooser.APPROVE_OPTION) { 
       File selectedFile = fileChooser.getSelectedFile(); 
       System.out.println("Selected file: " + selectedFile.getAbsolutePath()); 
       String content = readFile(selectedFile, StandardCharsets.UTF_8); 
       System.out.println(content); 
       textArea.setText(content); 
      } 

     } 

     private String readFile(File selectedFile, Charset utf8) { 
      // TODO Auto-generated method stub 
      return null; 
     } 
    } 
); 

回答

0

你可以看看该参数必须是从Component类型API。那么this在你的例子中是什么意思?您的课程有哪些其他课程/界面extendsimplements

您没有粘贴readFile方法的代码,但询问它为什么返回null?这样我们不能帮你,所以请发布代码。

+0

我很愚蠢,在我的readfile方法中看起来不太多,谢谢你指出了这一点,这使我朝着正确的方向发展,现在已经修好了,非常感谢! – 221flo221