0

My GUI application allows users to type into a JTextField object stating the name of a file to open and display its contents onto a JTextArea object. If the entered information consists of the file name then it shall retrieve its contents otherwise, in other case, it shall be a directory then it shall display the files and folders. Right now, I'm stuck as in the setText() of my JTextArea does not display contents correctly. It only display once which means to say there's some problem with my while loop. Could you guys help me out here please?

Please note the code below has been altered to the correct working version provided all the helpful contributors below.

Main class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

class MyFileLister extends JPanel implements ActionListener {

private JLabel prompt = null;

private JTextField userInput = null;

private JTextArea textArea = null;

public MyFileLister()
{
    prompt = new JLabel("Enter filename: ");
    prompt.setOpaque(true);
    this.add(prompt);

    userInput = new JTextField(28);
    userInput.addActionListener(this);
    this.add(userInput);

    textArea = new JTextArea(10, 30);
    textArea.setOpaque(true);
    JScrollPane scrollpane = new JScrollPane(textArea);
    this.add(textArea, BorderLayout.SOUTH);
}

Scanner s = null;
File af = null;
String[] paths;

public void actionPerformed(ActionEvent f)
{
    try
    {
        s = new Scanner(new File(userInput.getText()));

        while(s.hasNextLine())
        {
            String as = s.nextLine();
            textArea.append(as + "\n");
            textArea.setLineWrap(truea);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
        System.out.println(Arrays.toString(paths));

        String tempPath = "";
        for(String path: paths)
        {
            tempPath += path + "\n";
        }

        textArea.setText(tempPath);
    }
}
}

Driver class:

import java.util.*;
import java.awt.*;
import javax.swing.*;


class TestMyFileLister {

public static void main(String [] args)
{
    MyFileLister thePanel = new MyFileLister();

    JFrame firstFrame = new JFrame("My File Lister");

    firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    firstFrame.setVisible(true);
    firstFrame.setSize(500, 500);
    firstFrame.add(thePanel);


}
}

Here's one of the screenshot which I have to achieve. It shows that when the user's input is on a directory it displays the list of files and folders under it.

screenshot_directory

I tried to put in an if statement to see if I can slot in a show message dialog but I seriously have no idea where to put it.

public void actionPerformed(ActionEvent f)
{       
    try
    {
        s = new Scanner(new File(userInput.getText()));

        if(af == null)
        {
            System.out.println("Error");
        }

        while(s.hasNextLine())
        {
            String as = s.nextLine();
            textArea.append(as + "\n");
            textArea.setLineWrap(true);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
        System.out.println(Arrays.toString(paths));

        String tempPath = "";
        for(String path: paths)
        {
            tempPath += path + "\n";
        }

        textArea.setText(tempPath);
    }   
}
Scorpiorian83
  • 469
  • 1
  • 4
  • 17
  • 3
    Maybe you want to use `textArea.append()` instead of `textArea.setText()`. The latter will overwrite the previous iteration – Paul Samsotha Aug 28 '14 at 16:16
  • See [How to use Text Areas](http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html) – Paul Samsotha Aug 28 '14 at 16:21
  • You should probably also `textArea.setLineWrap(true); textArea.setWrapStyleWord(true);` See [JTextArea API](http://docs.oracle.com/javase/8/docs/api/javax/swing/JTextArea.html) – Paul Samsotha Aug 28 '14 at 16:23
  • If this isn't for an assignment, there is already a java class that pretty much does what you're trying to do: JFileChooser - http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html – mbw Aug 28 '14 at 18:07
  • @Scorpiorian83 I posted my answer let me know how it went – Kick Buttowski Aug 28 '14 at 19:16

2 Answers2

2

Code:

public void actionPerformed(ActionEvent ae) {
        try (Scanner s = new Scanner(new File(userInput.getText()))) {
            while (s.hasNextLine()) {
                String as = s.nextLine();
                textArea.append(as + "\n");
                textArea.setLineWrap(true);

            }

        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this,
                    "File not found",
                    "No File Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

Notes:

  1. Just try to read your file line by line so you can copy the same structure from your file into your JTextArea.
  2. Use setLineWrap method and set it to true read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)

  3. use append method in order to add text to end of your JTextArea read here http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)

  4. Use JOptionPane to show error message to an user

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • hey hi thanks so much for spending the efforts! yeah it kinda worked for me but I have to achieve the scrollbar for the string wrap and if the user's input is not the file but a directory, it will display the list of files and folders under it and display onto the `JTextArea`. I just edited the question to show the screenshot. Cheers! – Scorpiorian83 Aug 28 '14 at 19:24
  • what is the issue now? – Kick Buttowski Aug 28 '14 at 19:27
  • erm the screenshot is what is expected of the application to achieve. Right now, I still unable to achieve that stage yet lol. – Scorpiorian83 Aug 28 '14 at 19:31
2

You're outputting text to textArea based on the Last File on the list !!! ( don't set your text to JTextArea directly inside a loop, the loop is fast and the UI can't render it, so concatenate the string then set it later after the loop finishes ).

     // These lines below are causing only last file shown.

    for(String path: paths)
    {
        textArea.setText(path);
    }

Here is your modified version for MyFileLister class :

public class MyFileLister extends JPanel implements ActionListener {

private JLabel prompt = null;  
private JTextField userInput = null;    
private JTextArea textArea = null;

public MyFileLister()
{
    prompt = new JLabel("Enter filename: ");
    prompt.setOpaque(true);
    this.add(prompt);

    userInput = new JTextField(28);
    userInput.addActionListener(this);
    this.add(userInput);

    textArea = new JTextArea(10, 30);
    textArea.setOpaque(true);
    JScrollPane scrollpane = new JScrollPane(textArea);
    this.add(scrollpane, BorderLayout.SOUTH);
}

Scanner s = null;
File af ;
String[] paths;

public void actionPerformed(ActionEvent f)
{
    try
    {
        s = new Scanner(new File(userInput.getText()));

        while(s.hasNext())
        {
            String as = s.next();
            textArea.setText(as);
        }

    }
    catch(FileNotFoundException e)
    {
        af = new File(userInput.getText());

        paths = af.list();
       System.out.println(Arrays.toString(paths));

       String tempPath=""; 
        for(String path: paths)
        {
           tempPath+=path+"\n";

        }
        textArea.setText(tempPath);

    }
}
}

Output :

enter image description here

Fevly Pallar
  • 3,059
  • 2
  • 15
  • 19
  • hey hi Fev! thanks to your help as well I manage to get the application working now but I still have few small issues here. the first one is my scrollbar is not appearing at all and the next issue is for the coding provided by Kick the exception handling which shows a message dialog, I wish to use it as well but for my exception handling I'm using it for the file directory thingy. Do you have any suggestion? Thanks! – Scorpiorian83 Aug 29 '14 at 10:01
  • 1
    your scrollbar is not appearing at all because `this.add(textArea, BorderLayout.SOUTH);` should be `this.add(scrollpane, BorderLayout.SOUTH);` there is also typo `textArea.setLineWrap(truea);` should be `textArea.setLineWrap(true);`. And for the JOptionPane, you should can solve it by yourself. Btw don't edit your question based on answer (my answer) !!! so we could see clearly what you problem are. – Fevly Pallar Aug 29 '14 at 11:00
  • oh yes I got the scrollbar working now thanks for your help but one thing i don't understand is how come for the `JTextArea` I don't have to `add` it to the `Panel`? Regarding the JOptionPane I seriously can't get it right coz I reckon that it must be in the `ActionPerformed` event handling section right? :S – Scorpiorian83 Aug 29 '14 at 11:23
  • Here is the flow : 1). you add JTextArea to JScrollPane by declaring `JScrollPane scrollpane = new JScrollPane(textArea);`, 2). so now because JScrollPane itself has JTextArea so you add JScrollPane (which is containing JTextArea ) to frame by declaring `this.add(scrollpane, BorderLayout.SOUTH);`. And for the JOptionPane, seriously you can solve it yourself, just put it inside the correct area when you catch the exception (beside it's out of range for your real problems). – Fevly Pallar Aug 29 '14 at 11:32