Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 34

Thread: From Console to GUI : problem !!

  1. #1
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default From Console to GUI : problem !!

    Hello guys, I'm a complete GUI noob, I wrote a piece of code that searches for a given file type in a given location and displays all those files on console. I want to make a GUI for this program that consists of four components, two textfields (one for path, one for file type), one button that starts the search and I want the result to be displayed on a textarea just like they are displayed on console. Could anyone help me identifying the problem with my code?


    EDIT : I made the interface with NetBeans this type, edited a bit the code, but still the very same problem. here is the new code though :
    Window class :
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /*
     * Window.java
     *
     * Created on 19 août 2011, 16:21:43
     */
    /**
     *
     * @author Turki
     */
    import java.util.*;
    import java.io.*;
    public class Window extends javax.swing.JFrame {
     
        /** Creates new form Window */
        public Window() {
            initComponents();
        }
     
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
     
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            filetype = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            path = new javax.swing.JTextField();
            jPanel2 = new javax.swing.JPanel();
            jLabel3 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            result = new javax.swing.JTextArea();
            nowsearching = new javax.swing.JLabel();
            searchbutton = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel1.setText("File Type");
     
            jLabel2.setText("Search Path");
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(filetype, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(path))
                    .addContainerGap(79, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(filetype, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(21, Short.MAX_VALUE))
            );
     
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel3.setText("Search Result");
     
            result.setColumns(20);
            result.setEditable(false);
            result.setRows(5);
            jScrollPane1.setViewportView(result);
     
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                        .addComponent(nowsearching))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
                    .addGap(9, 9, 9)
                    .addComponent(nowsearching))
            );
     
            searchbutton.setText("Search");
            searchbutton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    searchbuttonActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(searchbutton)
                            .addGap(25, 25, 25))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(searchbutton)
                    .addContainerGap(67, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>
     
        private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            File file = new File(path.getText());
            File[] list = file.listFiles();
            FileSearch f = new FileSearch();
            f.search(list, filetype.getText(), result, nowsearching);
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                public void run() {
                    new Window().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JTextField filetype;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel nowsearching;
        private javax.swing.JTextField path;
        private javax.swing.JTextArea result;
        private javax.swing.JButton searchbutton;
        // End of variables declaration
    }


    And this is the FileSearch class :
     
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class FileSearch {
    	static void search(File[] list, String letype, JTextArea result, JLabel nowsearching  ){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< list.length; i++){
    		// Tell the user where it is searching
    			nowsearching.setText(list[i].toString());
    			if (list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((list[i].toString().endsWith(letype))){
     
    				result.append(list[i].getName());
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			list = folders.get(i).listFiles();
    			search(list,letype, result, nowsearching);
    		}
     
    	}
     
     
    }

    First off, the layout is extremely ugly haha ! dunno how to fix it. Any tips? good tutorials?
    Secondly, the program almost die when I click the search button !
    When I change it to display results on console, it works perfectly well !


    Thanks a lot in advance
    Last edited by hexwind; August 19th, 2011 at 10:50 AM.
    My website : MediDev


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: From Console to GUI : problem !!

    You could just use a JFileChooser.
    Improving the world one idiot at a time!

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by hexwind View Post
    Could anyone help me identifying the problem with my code?
    Any chance you can explain what the problem is? Are you getting error messages? Copy and paste them here. Are you getting incorrect behaviour? Then describe what is happening and what should happen instead.
    Improving the world one idiot at a time!

  4. #4
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by hexwind View Post

    First off, the layout is extremely ugly haha ! dunno how to fix it. Any tips? good tutorials?
    Secondly, the program almost die when I click the search button !
    When I change it to display results on console, it works perfectly well !


    Thanks a lot in advance
    Quote Originally Posted by Junky View Post
    Any chance you can explain what the problem is? Are you getting error messages? Copy and paste them here. Are you getting incorrect behaviour? Then describe what is happening and what should happen instead.
    Sorry if i didn't express myself properly lol.
    My problem is, when I run this program, the elements of the GUI are not well arranged. I don't know what is wrong with my code, but I want the elements to be one below the other.
    Second thing is, when I use the same code (without GUI) on a console, I give it the type of files to look for and the path, and it displays the results CORRECTLY on console. But with the GUI, I want to it to display the result on a TextArea, it does not and the program freezes.
    My website : MediDev

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: From Console to GUI : problem !!

    I want the elements to be one below the other.
    There are classes that will "layout" the components in a container called layout managers.
    Read the tutorial about the different choices and how to use them.
    Go to this site and Find Layout
    The Really Big Index

  6. #6
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    The program finally worked ! It just had to take sometime to search through my hard drive for the files and all and I thought it was frozen !

    EDIT : I wanted to tell the user that the program is searching for files and that it may take a while once they click the "search" button. here is the code :
     private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
            nowsearching.setText("Please wait, the search may take a while");
            File file = new File(path.getText());
    	File[] list = file.listFiles();
            FileSearch f = new FileSearch();
            f.search(list, filetype.getText().toString(), result);
             nowsearching.setText("Finished!");
        }

    the program seems that it's frozen, I don't see the message "Please wait" I just get the "Finished!" message. Any ideas?
    Last edited by hexwind; August 19th, 2011 at 11:23 AM.
    My website : MediDev

  7. #7
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    It's the AWT event thread that is executing the code in your actionPerformed so it won't be able to also repaint the Text until your actionPerformed method finishes (I think). Could you Thread your FileSearch and add your GUI as a Listener to FileSearch, so that it could notify your GUI of progress?
    Last edited by Sean4u; August 19th, 2011 at 11:38 AM. Reason: too much 'I think'

  8. #8
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Sean4u View Post
    It's the AWT event thread that is executing the code in your actionPerformed so it won't be able to also repaint the Text until your actionPerformed method finishes (I think). Could you Thread your FileSearch and add your GUI as a Listener to FileSearch, so that it could notify your GUI of progress?
    I don't have any idea how to do this. Could you help me please? or suggest any other way to tell the user that the program is not frozen but it's just taking time.
    My website : MediDev

  9. #9
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    You always create a new FileSearch object every time you search, so one way you could do this would be to make FileSearch into a Thread (by extending Thread, for example - see the Thread API docs for different ways of starting Threads). Then in your FileSearch constructor you could pass the search criteria, so a single FileSearch object is responsible for a single search. Since it's a little project of your own, there's no need to create special Listener interfaces to connect the two objects (GUI and FileSearch), you could just add an argument to the FileSearch constructor which was a 'YourGUIClass listener'. Then at the start of your FileSearch run method, call listener.notify("search started"), at intervals call (for example listener.notify("entering /home/me/projects/search/src/util") ) and at the end call listener.notify("search complete"). In your GUI object, have a method called notify that accepts strings from the FileSearch object and - at worst - sticks them straight into a text field.

    That should work. The basic requirement is to have two separate threads - one to handle your GUI events and updates, the other to do the searching. Passing in a 'this' for the GUI when you launch a new FileSearch will give it a reference on which it can invoke notify() (method you must write) to give the GUI clues about what it's doing.

  10. #10
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    Just in case it helps, here's a little program that demonstrates the idea:
    public class SimpleNotify
    {
      private boolean keepRunning = true;
      /* Class static code runs before any method is invoked.
         You can start an application this way, but the JVM
         *will* complain that there's no main method *and*
         it will return an error exit value. Doing it this way is
         a bit of fun, but ultimately wrong */
      static
      { new SimpleNotify(); }
      public SimpleNotify()
      {
        System.out.println("Welcome to SimpleNotify!");
        new Counter(this).start();
        // tie up this thread so we 'know' it's
        // not this thread calling notify
        while (keepRunning)
        {
          System.out.print(".");
          try
          { Thread.currentThread().sleep(300); }
          catch (Exception e)
          { e.printStackTrace(); }
        }
        System.out.println("I'm out");
      }
      public void notify(String s)
      {
        System.out.println("Notification received: " + s);
        if (s.equals("Finished!"))
          keepRunning = false;
      }
    }
    class Counter extends Thread
    {
      private SimpleNotify listener;
      public Counter(SimpleNotify notificationReceiver)
      {
        super("Counter");
        listener = notificationReceiver;
      }
      private int count = 0;
      @Override
      public void run()
      {
        listener.notify("Starting!");
        while (count++ < 100)
        {
          try
          { sleep(100); }
          catch (Exception e)
          { e.printStackTrace(); }
          if (count % 10 == 0)
            listener.notify("Reached " + count);
        }
        try
        { sleep(1000); }
        catch (Exception e)
        { e.printStackTrace(); }
        listener.notify("Finished!");
      }
    }
    Last edited by Sean4u; August 19th, 2011 at 04:54 PM. Reason: Comment on static initialization code

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: From Console to GUI : problem !!

    Learned something new today. Never thought about when a static block is called relative to the calling of the constructor or the main method.
    A note in your code could help a newbie understand what is going on.

  12. #12
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    I think I must learn more about threads, cause I couldn't understand the code or the idea properly !
    Thanks for your help though
    My website : MediDev

  13. #13
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    A note in your code
    Done. I occasionally employ that in trial code when I'm pushed for time, it works - but the error exit code from the JVM is a fatal side-effect.

  14. #14
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Sean4u View Post
    You always create a new FileSearch object every time you search, so one way you could do this would be to make FileSearch into a Thread (by extending Thread, for example - see the Thread API docs for different ways of starting Threads). Then in your FileSearch constructor you could pass the search criteria, so a single FileSearch object is responsible for a single search. Since it's a little project of your own, there's no need to create special Listener interfaces to connect the two objects (GUI and FileSearch), you could just add an argument to the FileSearch constructor which was a 'YourGUIClass listener'. Then at the start of your FileSearch run method, call listener.notify("search started"), at intervals call (for example listener.notify("entering /home/me/projects/search/src/util") ) and at the end call listener.notify("search complete"). In your GUI object, have a method called notify that accepts strings from the FileSearch object and - at worst - sticks them straight into a text field.

    That should work. The basic requirement is to have two separate threads - one to handle your GUI events and updates, the other to do the searching. Passing in a 'this' for the GUI when you launch a new FileSearch will give it a reference on which it can invoke notify() (method you must write) to give the GUI clues about what it's doing.

    okay mister, I changed my FileSearch class like this
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class FileSearch extends Thread{
     
    	 public FileSearch(File[] list, String letype, JTextArea result  ){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< list.length; i++){
    		// Tell the user where it is searching
     
    			if (list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((list[i].toString().endsWith(letype))){
     
    				result.append(list[i].getName()+"\n");
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			list = folders.get(i).listFiles();
    			new FileSearch(list,letype, result);
    		}
     
    	}
     
     
    }

    and the ActionPerformed method as follow
     
    private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
     
            setCursor(Cursor.WAIT_CURSOR);
            result.setText("");
     
     
            File file = new File(path.getText());
    	File[] list = file.listFiles();
             FileSearch f = new FileSearch(list, filetype.getText().toString(), result);
             f.start();
             nowsearching.setText("Search has started");
           setCursor(Cursor.DEFAULT_CURSOR);
             nowsearching.setText("Finished!");
        }
    It didn't work!
    My website : MediDev

  15. #15
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    Have another look at the API docs for java.lang.Thread. Your constructor should just be used to pass in the resources the thread will use *while it is searching*. The actual searching itself should be done inside the run() method. You'll need some data members in the FileSearch instance that can be assigned by the constructor. It'll be those data members that the run() method will still have access to once the Thread actually starts its independent life.

  16. #16
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Sean4u View Post
    Have another look at the API docs for java.lang.Thread. Your constructor should just be used to pass in the resources the thread will use *while it is searching*. The actual searching itself should be done inside the run() method. You'll need some data members in the FileSearch instance that can be assigned by the constructor. It'll be those data members that the run() method will still have access to once the Thread actually starts its independent life.
    ok, I tried to do as you suggested and as I understood :

     
     
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class FileSearch extends Thread{
        private File[] list;
        private String letype;
        private JTextArea result;
     
     
     
     
     	 public FileSearch(File[] list, String letype, JTextArea result  ){
                 this.list = list;
                 this.letype = letype;
     
             }
     
     
     
             public void run(){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< this.list.length; i++){
     
     
    			if (this.list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(this.list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((this.list[i].toString().endsWith(this.letype))){
     
    				result.append(this.list[i].getName()+"\n");
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			this.list = folders.get(i).listFiles();
    			new FileSearch(this.list,this.letype, result);
    		}
     
    	}
     
     
    }

     private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
            nowsearching.setText("Search has started");
            setCursor(Cursor.WAIT_CURSOR);
            result.setText("");
     
     
            File file = new File(path.getText());
    	File[] list = file.listFiles();
             FileSearch f = new FileSearch(list, filetype.getText().toString(), result);
            f.run();
     
           setCursor(Cursor.DEFAULT_CURSOR);
             nowsearching.setText("Finished!");
        }
    What about the rest? i read your other post about notify and I did not understand it properly.
    I tried to use a progression bar instead, it seemed even more complicated..


    EDIT: After reading your posts again. let me summarize what I understood
    I have to create two threads that I lunch in the ActionPerformed method of my search button. One thread will take care of the searching (I basically have to turn FileSearch into a thread by extending the class to Thread). and another thread that will take strings from FileSearch thread (strings that indicate where the search is occuring for example) and then display the info on the GUI (JLabel).
    no?
    Last edited by hexwind; August 19th, 2011 at 10:36 PM.
    My website : MediDev

  17. #17
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    I have to create two threads
    No, you already have two threads. One thread is the AWT event thread which is what invokes your actionPerformed method and is also responsible for updating any GUI fields you update (so the actionPerformed method must finish first before the AWT event thread can deal with the field you update from within it). Your search is long-lived, so you must start a thread from within your actionPerformed method which performs the search. It looks from your code like you're nearly there.

    In the constructor of your FileSearch thread you must pass in the search data, but also some reference to something in your GUI that FileSearch can use to pass back messages to the GUI. If you don't like the idea of passing in a reference to your whole GUI class and using a 'notify'-like method, you could pass in your Swing control as you are now. You don't save the reference to the Swing control in the constructor, so you can't refer to it in the run() method. You need to do that. Then in your run method, at the beginning and the end, and perhaps at intervals while the search is running (when the directory changes, for example) you change the Swing control text. Something like:
    public void run()
    {
      resultControl.setText("FileSearch starting");
      /* your big search loop */
      while(/*whatever*/)
        for(File dir : getDirectories())
        {
          resultControl.setText("Searching in " + dir);
          /* awesome filesearching code */
        }
      resultControl.setText("FileSearch finished");
    }
    That would work to update your GUI because your actionPerformed method would terminate quickly, freeing up the AWT event thread to handle any control updates performed by FileSearch in *its own* thread.

    Passing a reference to a Swing control like this would work, but it's obviously limited in terms of communication between the FileSearch thread and your GUI. If you used a Listener-like pattern (referred to as 'callbacks' in other languages), then you would pass a meaningful message - as a String or as a more structured object like AWT does for ActionEvent - from the 'acting' thread to the 'listening' code which could then decide what kind of response to make. As your code is now, the only response is that a text field is updated - your application doesn't in any sense *know* that the state of the FileSearch object has changed. If you used a notify() method (you don't have to call it notify()) then your application could read the message and do possibly lots of different things with it: update a text field, update a progress bar, play some sound, raise a dialog, even shut down.
    Last edited by Sean4u; August 20th, 2011 at 05:32 AM. Reason: apostrophe's

  18. #18
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Sean4u View Post
    No, you already have two threads. One thread is the AWT event thread which is what invokes your actionPerformed method and is also responsible for updating any GUI fields you update (so the actionPerformed method must finish first before the AWT event thread can deal with the field you update from within it). Your search is long-lived, so you must start a thread from within your actionPerformed method which performs the search. It looks from your code like you're nearly there.

    In the constructor of your FileSearch thread you must pass in the search data, but also some reference to something in your GUI that FileSearch can use to pass back messages to the GUI. If you don't like the idea of passing in a reference to your whole GUI class and using a 'notify'-like method, you could pass in your Swing control as you are now. You don't save the reference to the Swing control in the constructor, so you can't refer to it in the run() method. You need to do that. Then in your run method, at the beginning and the end, and perhaps at intervals while the search is running (when the directory changes, for example) you change the Swing control text. Something like:
    public void run()
    {
      resultControl.setText("FileSearch starting");
      /* your big search loop */
      while(/*whatever*/)
        for(File dir : getDirectories())
        {
          resultControl.setText("Searching in " + dir);
          /* awesome filesearching code */
        }
      resultControl.setText("FileSearch finished");
    }
    That would work to update your GUI because your actionPerformed method would terminate quickly, freeing up the AWT event thread to handle any control updates performed by FileSearch in *its own* thread.

    Passing a reference to a Swing control like this would work, but it's obviously limited in terms of communication between the FileSearch thread and your GUI. If you used a Listener-like pattern (referred to as 'callbacks' in other languages), then you would pass a meaningful message - as a String or as a more structured object like AWT does for ActionEvent - from the 'acting' thread to the 'listening' code which could then decide what kind of response to make. As your code is now, the only response is that a text field is updated - your application doesn't in any sense *know* that the state of the FileSearch object has changed. If you used a notify() method (you don't have to call it notify()) then your application could read the message and do possibly lots of different things with it: update a text field, update a progress bar, play some sound, raise a dialog, even shut down.

    Here is my code. Now it doesn't perform the search at all !
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
     
    public class FileSearch extends Thread{
     
        File[] list;
        String letype;
        JTextArea result;
        JLabel label;
     	 public FileSearch(File[] list, String letype, JTextArea result, JLabel label  ){
                 this.letype = letype;
                 this.list = list;
                 this.label = label;
                 this.result= result;
             }
     
             public void run(){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< this.list.length; i++){
    		// Tell the user where it is searching
    			this.label.setText("Now searching in " + this.list[i].getPath().toString());
    			if (this.list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(this.list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((this.list[i].toString().endsWith(this.letype))){
     
    				this.result.append(this.list[i].getName()+"\n");
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			this.list = folders.get(i).listFiles();
    			new FileSearch(this.list,this.letype, this.result,this.label);
    		}
     
    	}
     
     
    }

    Tell me, did you try to compile my original code? maybe you should to see where the problem lies !
    Thanks a lot for bearing with me
    My website : MediDev

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: From Console to GUI : problem !!

    Now it doesn't perform the search at all !
    Can you explain what it does do?
    Does the run method get executed?

    Can you post ALL of your current code?

  20. #20
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Here is my FileSearch code :
     
     
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
     
    public class FileSearch extends Thread{
     
        File[] list;
        String letype;
        JTextArea result;
        JLabel label;
     	 public FileSearch(File[] list, String letype, JTextArea result, JLabel label  ){
                 this.letype = letype;
                 this.list = list;
                 this.label = label;
                 this.result= result;
             }
     
             public void run(){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< this.list.length; i++){
    		// Tell the user where it is searching
    			this.label.setText("Now searching in " + this.list[i].getPath().toString());
    			if (this.list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(this.list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((this.list[i].toString().endsWith(this.letype))){
     
    				this.result.append(this.list[i].getName()+"\n");
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			this.list = folders.get(i).listFiles();
    			new FileSearch(this.list,this.letype, this.result,this.label);
    		}
     
    	}
     
     
    }

    The Window class :

     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /*
     * Window.java
     *
     * Created on 19 août 2011, 16:21:43
     */
    /**
     *
     * @author Turki
     */
    import java.util.*;
    import java.io.*;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    import javax.swing.SwingWorker;
     
    import java.awt.*;
    public class Window extends javax.swing.JFrame {
     
        /** Creates new form Window */
        public Window() {
            initComponents();
        }
     
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            filetype = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            path = new javax.swing.JTextField();
            jPanel2 = new javax.swing.JPanel();
            jLabel3 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            result = new javax.swing.JTextArea();
            nowsearching = new javax.swing.JLabel();
            jProgressBar1 = new javax.swing.JProgressBar();
            searchbutton = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel1.setText("File Type");
     
            jLabel2.setText("Search Path");
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(filetype, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(path))
                    .addContainerGap(79, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(filetype, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(21, Short.MAX_VALUE))
            );
     
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel3.setText("Search Result");
     
            result.setColumns(20);
            result.setEditable(false);
            result.setRows(5);
            result.setText("The result will be shown here");
            jScrollPane1.setViewportView(result);
     
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addComponent(nowsearching)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(nowsearching))
            );
     
            searchbutton.setText("Search");
            searchbutton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    searchbuttonActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(searchbutton))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(searchbutton)
                    .addContainerGap(40, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
     
            setCursor(Cursor.WAIT_CURSOR);
            result.setText("");
     
     
            File file = new File(path.getText());
            File[] list = file.listFiles();
            FileSearch f = new FileSearch(list, filetype.getText().toString(), result, nowsearching);
            f.run();
     
     
     
     
     
     
     
           setCursor(Cursor.DEFAULT_CURSOR);
             nowsearching.setText("Finished!");
        }                                            
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                public void run() {
                    new Window().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JTextField filetype;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JProgressBar jProgressBar1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel nowsearching;
        private javax.swing.JTextField path;
        private javax.swing.JTextArea result;
        private javax.swing.JButton searchbutton;
        // End of variables declaration                   
    }

    Try to compile it and you 'll see. Apparently it's searching in one single folder. But it used to work perfectly. I just wanted to notify the user that the program isn't frozen as it seems but it's working. I wanted to display a message or a progress bar but I don't have a clue how to.
    (remmeber to put "\\" in the search path if u are on Windows)
    Last edited by hexwind; August 20th, 2011 at 12:22 PM.
    My website : MediDev

  21. #21
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: From Console to GUI : problem !!

    No, I didn't compile your original code. There is currently a fairly major problem in your run() method which probably worked (badly) before but now will not. Your FileSearch object is now a Thread. You only need one thread/object to do this search. What you do in your run() method is to scan the current file list, searching for files. If you find a directory, you add it to a folders list. At the end of the current list, you go through your folders list, and create a new FileSearch object for each directory in that list. That would have worked before, but now will not because FileSearch is a Thread and needs to be start()ed.

    My recommendation would be to put your for loop that scans the current directory inside a while loop that checks to see if the folders list is not empty (adding the initial directory to that list before you start the while), removing the directory at the head of the list each time for the for loop to work on. Then you'll only have a single FileSearch object that will recursively descend directories.

    The other alternative is to have a start a new FileSearch thread for every directory you encounter, but that ... has a number of problems. Dinner calls.

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: From Console to GUI : problem !!

    Try debugging your FileSearch class as a standalone program to be sure it does what you want. Try adding this main() method to your code and adding printlns for all the places where you add Strings to the textarea.
    System.out.println("Now searching in " + this.list[i].getPath().toString());
    ...
    System.out.println("dir:" + this.list[i].getName()+"\n"); // show when adding to list
    ...
    System.out.println("file:" + this.list[i].getName()+"\n");



      public static void main(String[] args) {
        File[] list = new File[]{new File("E:/Testing")};
        FileSearch fs = new FileSearch(list, "java", new JTextArea(), new JLabel());
        fs.start();
      }

  23. The Following User Says Thank You to Norm For This Useful Post:

    hexwind (August 20th, 2011)

  24. #23
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Norm View Post
    Try debugging your FileSearch class as a standalone program to be sure it does what you want. Try adding this main() method to your code and adding printlns for all the places where you add Strings to the textarea.
    System.out.println("Now searching in " + this.list[i].getPath().toString());
    ...
    System.out.println("dir:" + this.list[i].getName()+"\n"); // show when adding to list
    ...
    System.out.println("file:" + this.list[i].getName()+"\n");



      public static void main(String[] args) {
        File[] list = new File[]{new File("E:/Testing")};
        FileSearch fs = new FileSearch(list, "java", new JTextArea(), new JLabel());
        fs.start();
      }

    Actually, I wrote the code of FileSearch and run it on console. and then I wanted to create a GUI for it.
    So the FileSearch class works perfectly on a console but not with a GUI.
    I tried this code
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /*
     * Window.java
     *
     * Created on 19 août 2011, 16:21:43
     */
    /**
     *
     * @author Turki
     */
    import java.util.*;
    import java.io.*;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    import javax.swing.SwingWorker;
     
    import java.awt.*;
    public class Window extends javax.swing.JFrame {
     
        /** Creates new form Window */
        public Window() {
            initComponents();
        }
     
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            filetype = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            path = new javax.swing.JTextField();
            jPanel2 = new javax.swing.JPanel();
            jLabel3 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            result = new javax.swing.JTextArea();
            nowsearching = new javax.swing.JLabel();
            jProgressBar1 = new javax.swing.JProgressBar();
            searchbutton = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel1.setText("File Type");
     
            jLabel2.setText("Search Path");
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(filetype, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(path))
                    .addContainerGap(79, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(filetype, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(path, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(21, Short.MAX_VALUE))
            );
     
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
     
            jLabel3.setText("Search Result");
     
            result.setColumns(20);
            result.setEditable(false);
            result.setRows(5);
            result.setText("The result will be shown here");
            jScrollPane1.setViewportView(result);
     
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addComponent(nowsearching)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE))
                    .addContainerGap())
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(nowsearching))
            );
     
            searchbutton.setText("Search");
            searchbutton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    searchbuttonActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(searchbutton))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(searchbutton)
                    .addContainerGap(40, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
     
            setCursor(Cursor.WAIT_CURSOR);
            result.setText("");
     
     
            File file = new File(path.getText());
            File[] list = file.listFiles();
            FileSearch f = new FileSearch();
            f.search(list, filetype.getText(), result);
     
     
     
     
     
     
     
           setCursor(Cursor.DEFAULT_CURSOR);
             nowsearching.setText("Finished!");
        }                                            
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
     
                public void run() {
                    new Window().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JTextField filetype;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JProgressBar jProgressBar1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel nowsearching;
        private javax.swing.JTextField path;
        private javax.swing.JTextArea result;
        private javax.swing.JButton searchbutton;
        // End of variables declaration                   
    }

     
     
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
     
     
     
     
     
     
     
    public class FileSearch {
     
     
     
     	 public void search(File[] list, String letype, JTextArea result  ){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< list.length; i++){
    		// Tell the user where it is searching
     
    			if (list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((list[i].toString().endsWith(letype))){
     
    				result.append(list[i].getName()+"\n");
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			list = folders.get(i).listFiles();
    			 search(list,letype, result);
    		}
     
    	}
     
     
    }

    and it worked, but it doesn't notify the user of what's going on !
    My website : MediDev

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: From Console to GUI : problem !!

    The version you posted extended Thread. That is the one that needs testing and debugging.

    Or you need to change the code that creates the FileSearch object to do it in a new Thread instead of making FileSearch extend Thread.

  26. #25
    Member hexwind's Avatar
    Join Date
    May 2011
    Location
    Tunisia
    Posts
    48
    Thanks
    4
    Thanked 1 Time in 1 Post

    Default Re: From Console to GUI : problem !!

    Quote Originally Posted by Norm View Post
    The version you posted extended Thread. That is the one that needs testing and debugging.

    Or you need to change the code that creates the FileSearch object to do it in a new Thread instead of making FileSearch extend Thread.
    tested and it works well
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class FileSearch extends Thread{
    	static void run(File[] list, String letype  ){
     
    		// ArrayList that holds the directories		
    		List<File> folders = new ArrayList<File>();
     
    		// Loop through the directory, save sub-directories in the ArrayList and display the files
    		for (int i=0; i< list.length; i++){
    		// Tell the user where it is searching
    			System.out.println("**** searching in "+ list[i].getPath().toString()+"***");
    			if (list[i].isDirectory()) //if it's a directory then save it to the ArrayList
    				folders.add(list[i]);
    			//if it's file then display it on screen/save it another file
    			else if ((list[i].toString().endsWith(letype))){
     
    				System.out.println(list[i].getName());
    			}
     
    		}
     
    		//after filling the ArrayList with the sub-directories, get into each element (sub-directory) and repeat
    		// the process again
    		for (int i=0; i<folders.size(); i++){
    			list = folders.get(i).listFiles();
    			run(list,letype);
    		}
     
    	}
    	public static void main(String[] args) throws IOException {
    		Scanner scan = new Scanner(System.in);
     
    		// Ask user to input the type of file they are looking for
    		System.out.println("Input the file type (i.e \" .txt):");
    		String letype = scan.nextLine();
     
    		//Ask user to input the search location
    		System.out.println("Input the search path:");
    		String searchpath = scan.nextLine();
     
     
    		File file = new File(searchpath);
    		File[] list = file.listFiles();
     
    		run(list,letype);
    		System.out.println("Done!");
    	}
     
    }
    My website : MediDev

Page 1 of 2 12 LastLast

Similar Threads

  1. Having problems with output to console....help!
    By toppcon in forum What's Wrong With My Code?
    Replies: 21
    Last Post: July 13th, 2011, 06:38 PM
  2. Console box with scanner?
    By Hallowed in forum Java Theory & Questions
    Replies: 1
    Last Post: May 26th, 2011, 12:50 AM
  3. How do i run this Accounting console app?
    By mirzahat in forum AWT / Java Swing
    Replies: 2
    Last Post: November 16th, 2010, 12:22 AM
  4. Console Application - How to run it?
    By mirzahat in forum AWT / Java Swing
    Replies: 3
    Last Post: November 16th, 2010, 12:21 AM
  5. Problem with Console Input from Clipboard
    By Nilhanth in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: March 1st, 2010, 06:47 PM