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.

Results 1 to 3 of 3

Thread: Adding a frame/textarea to an application

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Adding a frame/textarea to an application

    So, I figured out how to get my folder monitoring code working, but now I would like to make it output into a window, rather than the console. I have both codes working separately but don't know how to merge them together into a single class. I realize that this is beginner stuff, but that's what I am

    This is the working folder monitor code:

    import net.contentobjects.jnotify.JNotify; 
    import net.contentobjects.jnotify.JNotifyListener;
     
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class FileWatcher { 
    	public void sample() throws Exception {
    	String path = "D:\\download"; 
    	System.out.println(path); 
    	int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; 
    	boolean watchSubtree = true; 
    	int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener()); 
    	Thread.sleep(1000000); 
    	boolean res = JNotify.removeWatch(watchID); 
    	if (!res) { 
    		System.out.println("Invalid"); 
    		} 
    	}
     
    	public void TouchFile(String fName) {
    		if ((fName.indexOf("Thumbs") == -1) || (fName.indexOf(".rar") == -1)){
    			String TodayDate = "";
    			String fModifyDate = "";
    	    	String line;
    	    	String line2 = "error";	    	
    			Calendar calendar = Calendar.getInstance();
    	        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    			File filename = new File(fName);        
    		 try {
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    	        TodayDate = dateFormat.format(calendar.getTime());	        
    	        fModifyDate = dateFormat.format(filename.lastModified());
    	    try {
    	    	Thread.currentThread().sleep(1000);
    	    	while ((line2.indexOf("error") != -1) && (!fModifyDate.equals(TodayDate))){
    		    System.out.println(fName + " modified on: " + fModifyDate);	    		
    	    	line2 = " ";
    	    	Process p = Runtime.getRuntime().exec("touch.exe " + "\"" + fName + "\"");
    	    	BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));	    	
    	          while ((line = input.readLine()) != null) {
    	            line2 = line2 + "\n" + line;
    	          }
    	          input.close();
    	          System.out.println(line2);
    	          p.waitFor();
    	    		}
    	    }
    	    catch (Exception err) {
    	    	err.printStackTrace();
    	    	}
    		}
    	  }
     
    class Listener implements JNotifyListener {
        public void fileRenamed(int wd, String rootPath, String oldName,
                String newName) {
            print("renamed " + rootPath + " : " + oldName + " -> " + newName);
        }
     
        public void fileModified(int wd, String rootPath, String name) {
            //print("modified " + rootPath + " : " + name);
            TouchFile(rootPath + "\\" + name);        
        }
     
        public void fileDeleted(int wd, String rootPath, String name) {
            print("deleted " + rootPath + " : " + name);
        }
     
        public void fileCreated(int wd, String rootPath, String name) {
            print("created " + rootPath + " : " + name);
            TouchFile(rootPath + "\\" + name);
        }
     
        void print(String msg) {
            System.err.println(msg);
        }
    }
    public static void main(String[] args) {
    	    try {
            new FileWatcher().sample();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     
    }

    This is is the working text area/window making code:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class Test extends JPanel implements ActionListener {
        protected JTextField textField;
        protected JTextArea textArea;
        private final static String newline = "\n";
     
        public Test() {
            super(new GridBagLayout());
     
            textField = new JTextField(20);
            textField.addActionListener(this);
     
            textArea = new JTextArea(5, 20);
            textArea.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(textArea);
     
            //Add Components to this panel.
            GridBagConstraints c = new GridBagConstraints();
            c.gridwidth = GridBagConstraints.REMAINDER;
     
            c.fill = GridBagConstraints.HORIZONTAL;
            add(textField, c);
     
            c.fill = GridBagConstraints.BOTH;
            c.weightx = 1.0;
            c.weighty = 1.0;
            add(scrollPane, c);
        }
     
        public void actionPerformed(ActionEvent evt) {
            String text = textField.getText();
            textArea.append(text + newline);
            textField.selectAll();
     
            //Make sure the new text is visible, even if there
            //was a selection in the text area.
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event dispatch thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Add contents to the window.
            frame.add(new Test());
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(String[] args) {
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    Last edited by zincc; March 5th, 2011 at 04:04 AM.


  2. #2
    Super Moderator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,235
    Thanks
    176
    Thanked 817 Times in 760 Posts
    Blog Entries
    5

    Default Re: Adding a frame/textarea to an application

    but don't know how to merge them together into a single class
    I'd recommend not merging them into a single class...(somewhat defeats the purpose of object oriented programming and reusable code). Rather, adapt FileWatcher so it can function independently of the other class as well as System.out. One way would be to modify FileWatcher to write to a PrintWriter (which System.out is an instance of) - this allows you to pass ANY PrintWriter to the class. Then should you want to get the information rather than print it the System.out, you can create a PrintWriter using a StringWriter
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    FileWatcher watcher = new FileWatcher(writer);//to write to the StringWriter.

    Now, every time the FileWatcher class does something it writes to StringWriter, whose value can be retrieved like this

    String value = sw.getBuffer().toString();
    If you want dynamic updating, you will have to adapt this method to notify when the StringWriter has been written to (if I haven't completely lost by now you and the above helps you out, we can deal with that issue should it come up)

  3. The Following User Says Thank You to copeg For This Useful Post:

    zincc (March 5th, 2011)

  4. #3
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Adding a frame/textarea to an application

    Hi copeg, thanks for your reply! I couldn't quite figure out how to use the code that you gave me but it did point me in a good direction and I got it the window logging to work in the end, after a lot of googling and trying things out.

    The code works now as I want it but I'd really appreciate it if someone could take a look and tell me if there are any glaring coding mistakes/bad practices in there. I'm pretty sure there are, as I suspect the way I use variables isn't the best, but there are probably others too.

    import net.contentobjects.jnotify.JNotify; 
    import net.contentobjects.jnotify.JNotifyListener;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JTextArea;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.SwingWorker;
    import javax.swing.JScrollPane;
    import java.util.logging.*;
    import java.awt.BorderLayout;
     
    public class FileWatcher extends JPanel {
    	private static String line2 = "error";
    	private JFrame frame = new JFrame();
            private JTextArea textArea = new JTextArea();
            private JScrollPane pane = new JScrollPane(textArea);	
    	private static FileWatcher watcher = new FileWatcher();
     
    	private void sample(String path) throws Exception {
    	showInfo("Monitoring: " + path);
    	int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; 
    	boolean watchSubtree = true; 
    	int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener()); 
    	Thread.sleep(1000000); 
    	boolean res = JNotify.removeWatch(watchID); 
    	if (!res) { 
    		//System.out.println("Invalid"); 
    		showInfo("Invalid"); 
    		} 
    	}
     
    	public void TouchFile(String fName) {
    		if ((fName.indexOf("Thumbs") == -1) && (fName.indexOf(".rar") == -1) && (fName.indexOf(".part") == -1)){
    			String TodayDate = "";
    			String fModifyDate = "";
    	    	String line;
    			Calendar calendar = Calendar.getInstance();
    	        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    			File filename = new File(fName);        
    		 try {
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    	        TodayDate = dateFormat.format(calendar.getTime());	        
    	        fModifyDate = dateFormat.format(filename.lastModified());
    	        try {
    	    	Thread.currentThread().sleep(1000);
    	    	while ((line2.indexOf("error") != -1) && (!fModifyDate.equals(TodayDate))){
    		//System.out.println(fName + " modified on: " + fModifyDate);	  
    		showInfo(fName + " modified on: " + fModifyDate);
    	    	line2 = " ";
    	    	Process p = Runtime.getRuntime().exec("touch.exe " + "\"" + fName + "\"");	    	
    	    	BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));	    	
    	          while ((line = input.readLine()) != null) {
    		      line2 = line2 + "\n" + line;
    	          }
    	          input.close();
    	          showInfo(line2);
    	          p.waitFor();
    	    		}
    	    }
    	    catch (Exception err) {
    	    	err.printStackTrace();
    	    	}
    		}
    	  }
     
    public void showInfo(String data) {
    	watcher.textArea.append(data+"\n");
    	watcher.frame.getContentPane().validate();
    	watcher.textArea.setCaretPosition(watcher.textArea.getText().length() - 1);
    }
     
    class Listener implements JNotifyListener {
        public void fileRenamed(int wd, String rootPath, String oldName,String newName) {
            //print("renamed " + rootPath + " : " + oldName + " -> " + newName);
            showInfo("renamed " + rootPath + "\\" + oldName + " -> " + newName);
        }
     
        public void fileModified(int wd, String rootPath, String name) {
            //print("modified " + rootPath + " : " + name);
            TouchFile(rootPath + "\\" + name);    
            showInfo("modified " + rootPath + "\\" + name);
        }
     
        public void fileDeleted(int wd, String rootPath, String name) {
            //print("deleted " + rootPath + " : " + name);
            showInfo("deleted " + rootPath + "\\" + name);
        }
     
        public void fileCreated(int wd, String rootPath, String name) {
            //print("created " + rootPath + " : " + name);
            TouchFile(rootPath + "\\" + name);
            showInfo(rootPath + "\\" + name);
        }
     
        void print(String msg) {
            //System.err.println(msg);
        	showInfo(msg);
        }
    }
    public static void main(String[] args) {
       String path = "H:\\download";
       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
       watcher.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        watcher.frame.setSize(500,200);
        watcher.frame.setVisible(true);	
        watcher.frame.getContentPane().add(watcher.pane);
        watcher.frame.setVisible(true); 
        watcher.frame.setLocation(screenSize.width-500,screenSize.height-250);
        try {
        	if (args.length > 0){
        		new FileWatcher().sample(args[0]);
        	}
        	else {
        		new FileWatcher().sample(path);
     
        	}
     
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    Last edited by zincc; March 5th, 2011 at 03:46 PM.

Similar Threads

  1. Store Values in 2D array and output to textarea
    By raverz1tildawn in forum What's Wrong With My Code?
    Replies: 4
    Last Post: January 7th, 2011, 02:13 PM
  2. TextArea and Array Problem
    By slippery_one in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 28th, 2010, 06:11 AM
  3. Trouble apending a textArea with the contents of a parameter
    By bluetxxth in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 21st, 2010, 03:28 PM
  4. Replies: 0
    Last Post: December 3rd, 2009, 03:43 PM
  5. The Frame to be Center Position
    By r12ki in forum AWT / Java Swing
    Replies: 3
    Last Post: October 1st, 2009, 10:36 AM