简体   繁体   中英

How to populate JTextArea with file from JList

Im creating an application that gets a list of .java and .class files from a chosen directory and places them in a JList. I am using Netbeans 7.1.2.

I have all the files being displaying in the JList like i want, what i cant seem to do is to open open the selected .java file in the jTextArea.

I need to get the file from the JList to pass it into the JTextArea but it is not working

     try
     {
         FileReader reader= new FileReader( jlist.getSelectedValue() );
         BufferedReader br = new BufferedReader( reader);
         textarea.read( br );
         br.close();
         textarea.requestFocus();               
     } 
     catch(Exception e2) {}

Does anybody see where im going wrong?

You need to use the read(...) method passing in a BufferedFileReader not the write(...) method if you are to read a file into a JTextArea. This should make sense to you since your goal here is to read, not to write.

textarea.write( bw );

Does this compile? write method seems to be meant for writing contents of textarea to a file not the other way around.

Also if something goes wrong, make sure not to catch the exception and ignore it. The exception trace can be very helpful in understanding what is going wrong.

If you're having trouble, you should be displaying/logging your exceptions, not swallowing them quietly. Your code could be encountering a problem that has a helpful exception associated with it, but you won't know until you write code that tells you about exceptions.

You could start with this:

try
{
     File file = (File)jlist.getSelectedValue();
     FileReader reader = new FileReader( file );
     textarea.read( br );
     br.close();
     textarea.requestFocus(); 
}
catch(Exception e)
{
    JOptionPane.showMessageDialog(null, e.toString());
}

As soon as you add something to a JList - A visual component - It's not longer a List of objects, as such. You just have an array with index 0 to n which you can pick from, but nothing is really IN them. What you COULD do would be make an array of Files (new File[]) and store all files in there so you can access them at any time.

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