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 16 of 16

Thread: Show files name in JFrame

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Show files name in JFrame

    Hi, and happy new year.
    I have this problem with my java learning.
    I want to create a GUI application which will read files on a directory and display they're names in the JFrame title and in a label in the frame.
    There are 2 classes: Start and ReadDirectory as below;

    HTML Code:
    //class Start
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.File;
    
    public class Start extends JFrame implements ActionListener {
    	private JPanel north, centre;
    	private JLabel label, label1;
    	private JTextField box;
    	private String f;
    	private JButton go;
    	private File folder;
    	private File[] listOfFiles;
    	public static void main( String[] args){
    	    JFrame frame = new Start();
    	    frame.setTitle("Start_JAVA");
    	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    frame.setSize(350,120); 
    	    frame.setVisible(true); 
    	} //end main
    	public Start(){
            centre = new JPanel();
            label1 = new JLabel("Enter folder's name ");
    	    box = new JTextField("",20);
    	    go = new JButton("Go");
    
            centre.add(label1); centre.add(box);centre.add(go);
    	    go.addActionListener(this);   // listen for button click
            add(centre, BorderLayout.CENTER);
    	}//end constructor
    	public void actionPerformed(ActionEvent ev) {
    	    String entry = box.getText();
    		folder = new File("C:\\Users\\Alti\\Desktop\\Altin\\be" + entry);
    	    listOfFiles = folder.listFiles();
    	    for (int i = 0; i < listOfFiles.length; i++) {
    	        if (listOfFiles[i].isFile()) {
    	    		f = listOfFiles[i].toString();
    	    		new ReadDirectory(f);
    	          }//end if
    	    }//end for
    	}//end actionPerformed
    }//END_______________________________________
    and the
    HTML Code:
    //class ReadDirectory
    import java.awt.*;
    import javax.swing.*;
    
    public class ReadDirectory extends JPanel{
    
      public ReadDirectory(String str) {
      JFrame frame = new JFrame(Start.f);
      frame.setSize(320, 170);
      Container contentPane = frame.getContentPane();
      contentPane.add(new ReadDirectory ());
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
      public ReadDirectory() {}
    	
      public void paint(Graphics g) {
        super.paint(g);
        g.setFont(new Font("Serif", Font.BOLD, 14));
        g.drawString(Start.f,32,25);
      }
    }
    My problem... I can see the file's name in the Frame's title, but the label is showing the last file's name???
    No idea where the problem is. Any help will be appreciated.
    Thank you.


  2. #2
    Junior Member
    Join Date
    Jan 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Hi,
    The code you entered makes 2 frames. This isn't working yet.

    I have picked some code from the internet. You should be able to print directories in the console by using the link and the following code: (you should alter the code a bit to get a function that returns files).

    Listing the Files or Subdirectories in a Directory | Example Depot

    public void actionPerformed(ActionEvent ev) {
            if(ev.getSource()==go){
                File[] subDirs = getSubDirectories("C:\\" + box.getText());
     
                for(int i = 0; i < subDirs.length; i++)
                    System.out.println(subDirs[i].toString());
     
            } else {
                System.out.println("weird action performed.");
            }
        }//end actionPerformed

    I dont think making a new JFrame and the labels is a problem for you.

  3. #3
    Junior Member
    Join Date
    Jan 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Hi

    Looked again it just works like this:

    package filenameresource2;
     
    //class ReadDirectory
    import java.awt.*;
    import javax.swing.*;
     
    public class ReadDirectory extends JPanel{
     
      public ReadDirectory(String str) {
          m_string = str;
     
      JFrame frame = new JFrame(str);
      frame.setSize(320, 170);
      Container contentPane = frame.getContentPane();
      contentPane.add(new ReadDirectory ());
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
      public ReadDirectory() {}
     
      public void paint(Graphics g) {
        super.paint(g);
        g.setFont(new Font("Serif", Font.BOLD, 14));
        g.drawString(m_string,32,25);
      }
     
      String m_string;
    }

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Show files name in JFrame

    Spoonfeeding is not helping.

    OP- One of your basic problems is that you're passing the String to display into each ReadDirectory, but then you're drawing the String from your Start class, which for some reason is updated each time you read a file name.

    You are also creating multiple JFrames for some reason, and you never add the ReadDirectory to your main JFrame.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    It counts the directories in the listofFiles also. not only the files


    check the output lke this:
    System.out.println(listOfFiles[i].toString());

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

    Default Re: Show files name in JFrame

    Looks like I forgotten to change the String f on the Start class; instead of private String f; is static String f;.
    Also I WANT to create multiple JFrames...maybe haven't explain clearly what I want...
    The problem is that every frame have the file's title, but label is overited and is showing only the last file as in:

    HTML Code:
    Frame                          Frame_Title                     Frame_Label
    1                                  a.txt                               c.txt
    2                                  b.txt                               c.txt
    3                                  c.txt                               c.txt
    
    I want it to be:
    
    Frame                          Frame_Title                     Frame_Label
    1                                  a.txt                               a.txt
    2                                  b.txt                               b.txt
    3                                  c.txt                               c.txt
    Last edited by altisw5; January 5th, 2011 at 12:07 PM.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Show files name in JFrame

    Again- You're painting Start.f, which you update each time you iterate, which means it will end up being the last value iterated over.

    You want to use the String you pass in to ReadDirectory's constructor.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. The Following User Says Thank You to KevinWorkman For This Useful Post:

    altisw5 (January 5th, 2011)

  9. #8
    Junior Member
    Join Date
    Jan 2011
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Thanks for pointing to the right direction.
    Actually I now got an:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: String is null
    at ReadDirectory.paint(ReadDirectory.java:22)

    The paint() is really hunting me.
    Never understood when is called....

  10. #9
    Junior Member
    Join Date
    Jan 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Hi again,

    I have looked at the code.

    The paint method is called:
    System-triggered Painting

    In a system-triggered painting operation, the system requests a component to render its contents, usually for one of the following reasons:

    * The component is first made visible on the screen.

    * The component is resized.

    * The component has damage that needs to be repaired. (For example, something that previously obscured the component has moved, and a previously obscured portion of the component has become exposed).
    In your program the m_string has not been initialized when you call your constructor ReadDirectory() { from ReadDirectory(String) .

    Look at this code very carefully

  11. #10
    Junior Member
    Join Date
    Jan 2011
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Or in your code Start.f gets called when the JPanel is painted. But is not initialized because of ReadDirectory().

  12. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Show files name in JFrame

    Why do you create an empty ReadDirectory in the ReadDirectory(String) constructor? You should be painting that supplied String.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #12
    Junior Member
    Join Date
    Jan 2011
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Why do you create an empty ReadDirectory in the ReadDirectory(String) constructor? You should be painting that supplied String.
    I have this "idea" that paint() is been called from constructor with no parameters.
    From your question can see that is totally not needed.

  14. #13
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Show files name in JFrame

    Quote Originally Posted by altisw5 View Post
    Why do you create an empty ReadDirectory in the ReadDirectory(String) constructor? You should be painting that supplied String.
    I have this "idea" that paint() is been called from constructor with no parameters.
    From your question can see that is totally not needed.
    Indeed. I'd be curious to see what your code looks like after taking that into consideration. Feel free to post an SSCCE (thats a link).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  15. #14
    Junior Member
    Join Date
    Jan 2011
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Show files name in JFrame

    Thanks guys.
    I got it right at the end.
    My ReadDirectory Class
    import java.awt.*;
    import javax.swing.*;
     
    public class ReadDirectory extends JPanel{
        String s;
        public ReadDirectory(String str) {
            s = str;
            JFrame frame = new JFrame(Start.f);
            frame.setSize(320, 170);
            Container contentPane = frame.getContentPane();
            contentPane.add(this);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
     
        public void paint(Graphics g) {
            super.paint(g);
            g.drawString(s,32,25);
        }
    }
    Really appreciate your help.

  16. #15
    Junior Member
    Join Date
    Nov 2011
    Posts
    1
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Thumbs down Re: Show files name in JFrame

    Hi guys
    My skill English is not good
    But I understand main content of this thread is "Show files name in JFrame" as IIS GUI.

    Example :

    I want a complete source about this feature
    Who can help me... ?
    I hope good everything to you
    Thanks you very much !!!

    I found a following code :
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package myjws;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
     
    /**
     *
     * @author ndp1007
     */
    public class DirectoryManament {
     
        public static File root = new File(".");
        public static void main(String[] argv){
     
            JTree tree = new JTree(new FileTreeModel(root));
            MouseAdapter ma = new MouseAdapter() {
                    private void myPopupEvent(MouseEvent e) {
                            int x = e.getX();
                            int y = e.getY();
                            JTree tree = (JTree)e.getSource();
                            TreePath path = tree.getPathForLocation(x, y);
                            if (path == null)
                                    return; 
                            tree.setSelectionPath(path);
     
                            Object obj = (Object)path.getLastPathComponent();
     
                            JPopupMenu popup = new JPopupMenu();
                             JMenuItem deleteItem = new JMenuItem("Deleted Virtual Directory");
                             JMenuItem addItem = new JMenuItem("Add Virtual Directory");
                              popup.add(addItem);
                              popup.addSeparator();
                              popup.add(deleteItem);
                             /*popup.add(new JMenuItem(label)).addItemListener(new ItemListener() {
     
                                @Override
                                public void itemStateChanged(ItemEvent e) {
                                    //throw new UnsupportedOperationException("Not supported yet.");
                                     System.out.print("hrhrhr");
                                }
                            });*/
                        deleteItem.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                //System.out.print(DirectoryManament.toString());
                                //e.get
                                    JOptionPane.showMessageDialog(null,
                                            "Deleted Virtual Directory");
                                }
                            });
                        addItem.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    JOptionPane.showMessageDialog(null,
                                            "Open Frame To Make VD");
                                }
                          });
     
                            popup.show(tree, x, y);
                    }
                    public void mousePressed(MouseEvent e) {
                            if (e.isPopupTrigger()) myPopupEvent(e);
                    }
                    public void mouseReleased(MouseEvent e) {
                            if (e.isPopupTrigger()) myPopupEvent(e);
                    }
            };
     
            tree.addMouseListener(ma);
     
     
            JScrollPane scrollpane = new JScrollPane(tree);	
            JFrame frame = new JFrame("Derectory Manament");	
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
            frame.getContentPane().add(scrollpane, "Center");	
            frame.setSize(400, 600);	
            frame.setVisible(true);  
        }
    }
    class FileTreeModel implements TreeModel {	
     
    // Chi ra thu muc root cua webserver	
    protected File root;	
    public FileTreeModel(File root) 	
    {	
        this.root = root;	
    }	
     
    // The model knows how to return the root object of the tree	
    public Object getRoot() 	
    {	
        return root;	
    }	
     
    // Tell JTree whether an object in the tree is a leaf or not	
    public boolean isLeaf(Object node) {	
        return ((File) node).isFile();	
    }	
     
    // Tell JTree how many children a node has	
    public int getChildCount(Object parent) {	
        String[] children = ((File) parent).list();	
        if (children == null) return 0;	
        return children.length;	
    }	
     
    // Fetch any numbered child of a node for the JTree.	
    // Our model returns File objects for all nodes in the tree.* The	
    // JTree displays these by calling the File.toString() method.	
    public Object getChild(Object parent, int index) {	
        String[] children = ((File) parent).list();	
        if ((children == null) || (index >= children.length)) 
            return null;	
        return new File((File) parent, children[index]);	
    }	
     
    // Figure out a child's position in its parent node.	
    public int getIndexOfChild(Object parent, Object child) {	
        String[] children = ((File) parent).list();	
        String childname = ((File) child).getName();	
        if (children == null) return -1;	
        for (int i = 0; i < children.length; i++) {	
            if(childname.equals(children[i])) return i;	
        }   	
        return -1;	
    }	
     
    // This method is only invoked by the JTree for editable trees.	
        public void valueForPathChanged(TreePath path, Object newvalue) {}	
    // Since this is not an editable tree model, we never fire any events,	
        public void addTreeModelListener(TreeModelListener l) {}	
        public void removeTreeModelListener(TreeModelListener l) {}	
    }
    Last edited by ndp1007; December 4th, 2011 at 11:52 AM.

  17. #16
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Show files name in JFrame

    Quote Originally Posted by ndp1007 View Post
    I want a complete source about this feature
    That is absolutely not how this works. If you want somebody to create the code for you, check out the Paid Java Projects forum from the main page. Otherwise, see the link in my signature before you post again.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  18. The Following User Says Thank You to KevinWorkman For This Useful Post:

    ndp1007 (December 4th, 2011)

Similar Threads

  1. How to show empty directories in JTree ?
    By ni4ni in forum AWT / Java Swing
    Replies: 1
    Last Post: April 30th, 2010, 12:55 AM
  2. JFrame declared as setAlwaysOnTop doesn't stay on top during slide show
    By ravindra_appikatla in forum AWT / Java Swing
    Replies: 1
    Last Post: March 30th, 2010, 09:08 AM
  3. Replies: 1
    Last Post: March 22nd, 2010, 04:34 PM
  4. Show Text With cursor
    By ravjot28 in forum AWT / Java Swing
    Replies: 1
    Last Post: January 20th, 2010, 10:02 AM
  5. How do i show all the values in one window(JOptionPane)??
    By Antonioj1015 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 25th, 2009, 09:24 PM