简体   繁体   中英

ShowopenDialog not working under actionlistener

So I have been trying to make a filechooser that opens a text file and then paste the contents in a JtextArea I have defined as textArea. But I cannot get my showOpenDialog to not give an error while having the argument (this), and I researched and the answer was to fill in (null) and this does make the filechooser work but when I try to print the contents of it it also just returns null. I am using the Eclipse program hence the auto filled code. I am fairly new to Java and have no clue what is going wrong. Im really sorry if this is not the way to post things here.

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;
        }
    }
);

You can look into the API that the parameter has to be from type Component . So what does this mean in your example? Which other class/interface does your class extends from or implements ?

You didn't paste the code of your readFile method but ask why it returns null? This way we cannot help you so please post the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM