简体   繁体   中英

Java: How to show the content of a file, opened by JFileChooser, in a JTextField?

I'm starting to learn Java and don't know how to show the content of a given file, that is opened by JFileChooser, in a JTextField

This is my code so far.

I deleted some imports and code for the better understanding of my program.

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){

Hope someone can help me!

File.getAbsolutePath() only returns the pathname. You're going to need to setText as the actual content of the file.

You can do this in a variety of ways. Here is one:

java.nio.file.Files.readAllLines(selectedFile.toPath(), Charset.defaultCharset());

for example, will return a List that you can join all together and setText on the JTextField to display all the content.

Suggestion: you might want to use a TextArea (shows multiple lines) instead. See: Loading a text file into a text area

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