Results 1 to 5 of 5
  1. #1
    jetnor is offline Member
    Join Date
    Jan 2011
    Location
    London
    Posts
    17
    Rep Power
    0

    Default Using a JFileChooser to get absolute path of a file

    Hi Guys,

    I am developing a program for data analysis. I am using Netbeans to develop a simple Desktop Application. I want to be able to make a JButton which opens a JFileChooser. I then want to be able to use the absolute path of the chosen file in another method which reads the data file.

    So to clarify things I have a class ReadData with a method called readFile(String filename), The filename is a string of the absolute path to the file.

    I have another class which is storing all the Graphical user interface components (JFrame, JPanel, JMenu). Now somehow I want to learn how to add a button to the GUI class which opens a file chooser popup box and the selected file path is passed on to the other method readFile(String filename) on class ReadData.

    I know how to make the button open a file chooser but I don't know how to add this button to the Graphical User Interface and I do not know how to use the result from the ActionListener . Below is some of the code that I have generated. I kind of understand how things work on their own but I don't know how to put them together. Any help is greatly appreciated as ever. :)

    Where would I create this button: In the ReadData Class and than add it to the GUI class or in the Gui Class and than use it's result in the ReadData Class?
    Java Code:
    //declare new button
     static JButton button1 = new javax.swing.JButton();
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            JFileChooser chooser = new JFileChooser();
            int returnName = chooser.showOpenDialog(null);
            String path;
    
            if (returnName == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                if (f != null) { // Make sure the user didn't choose a directory.
    
                    path = f.getAbsolutePath();//get the absolute path to selected file
                    //below line to test the file chooser
                    //System.out.println(path);
                }
            }
        }
    
        public void main(){
           // System.out.println(getFilePath());
            button1.setAction(null);
            button1.setName("Choose File");
            button1.addActionListener(new java.awt.event.ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
    
    
        }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You've got your Model, the ReadFile class, and your View, the GUI classes which all indicate a good separation of functionality into separate entities, now you will need to join them together with a Control class(es). Hang on a second and I'll show you an example of what I mean, an example of Model, View, Control or MVC...

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    First of all, assume for example purposes that your ReadData class is quite simple, something like so...

    Java Code:
    class ReadData {
        public void readFile(String fileName) {
            System.out.println("reading from " + fileName);
        }
    
        // overload the method so we can call it with a File parameter as well.
        public void readfile(File file) {
            System.out.println("reading from " + file.getAbsolutePath());
        }
    }


    And assume that your GUI is also very simple, something like so:

    Java Code:
    class GuiPanel extends JPanel {
        private Controller controller; // this will tie things together
    
    
        // pass a reference to the Controller in the GUI constructor
        GuiPanel(Controller controller) {
            this.controller = controller;
            
            JButton readFileBtn = new JButton("Read File");
            readFileBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    readFileBtnActionPerformed();
                }
            });
            JButton writeFileBtn = new JButton("Write File");
            writeFileBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    writeFileBtnActionPerformed();
                }
            });
            
            add(readFileBtn);
            add(writeFileBtn);
        }
    
        // call the Controller methods in the button's actionPerformed methods
        private void writeFileBtnActionPerformed() {
            if (controller != null) {
                controller.writeFileAction();
            }
        }
    
        // call the Controller methods in the button's actionPerformed methods
        private void readFileBtnActionPerformed() {
            if (controller != null) {
                controller.readFileAction();
            }
        }
    }

    And the Control class that ties all together could look something like so:

    Java Code:
    class Controller {
        private ReadData readData; // holds a reference to the "model", the ReadData object
    
    
        // set the Model's reference in the constructor
        public Controller(ReadData readData) {
            this.readData = readData;
        }
    
        public void readFileAction() {
            JFileChooser chooser = new JFileChooser();
            int returnName = chooser.showOpenDialog(null);
            String path;
            if (returnName == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                if (f != null) {
                    path = f.getAbsolutePath();
                    readData.readFile(path);
                }
            }
        }
        
        public void writeFileAction() {
            //.... code to write to file
            System.out.println("write to file");
        }
    }


    A Main class to create the JFrame and tie all together
    Java Code:
    public class Main {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createGui();
                }
            });
        }
    
        private static void createGui() {
            ReadData readData = new ReadData();
            Controller controller = new Controller(readData);
            GuiPanel guiPanel = new GuiPanel(controller);
            
            JFrame frame = new JFrame("App");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(guiPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }

  4. #4
    jetnor is offline Member
    Join Date
    Jan 2011
    Location
    London
    Posts
    17
    Rep Power
    0

    Default

    Dear Fubarable,

    Thank You for your very informative reply. I will now be trying to make it work. I suspect the autogenerated code from Netbeans Desktop Application will give me some headache. I will keep you updated.

    Regards,
    Jetnor.

  5. #5
    jetnor is offline Member
    Join Date
    Jan 2011
    Location
    London
    Posts
    17
    Rep Power
    0

    Default

    Hello Fubarable,

    I am stuck in one problem. Your code works very well and I have adapted it to work on my project.
    What I am stuck on is that I need to use the read file in another method called draw graph. This method runs when I add it to the Controller class but I want to be able to view the graph on a new JPanel object which I have created on the GuiPanel class. So the code with the draw graph method on the controller class is as below:
    Java Code:
    class Controller {
        private ReadData readData; // holds a reference to the "model", the ReadData object
    
    
        // set the Model's reference in the constructor
        public Controller(ReadData readData) {
            this.readData = readData;
        }
    
        public void readFileAction() {
            JFileChooser chooser = new JFileChooser();
            MatrixToGraph draw = new MatrixToGraph();
            int returnName = chooser.showOpenDialog(null);
            String path;
            if (returnName == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                if (f != null) {
                    path = f.getAbsolutePath();
    
                    double[][]rawData=ReadData.readDataMatrix(path, ",");
                    double[][]corrMatrix=CorrelationMatrix.readCorrMatrix(rawData);
                   draw.matixToGr(corrMatrix);
    
                }
            }
        }
    
        public void writeFileAction() {
            //.... code to write to file
            System.out.println("write to file");
        }
    }//End Class
    The updated controller class is as below:
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package fubarable;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    
    /**
     *
     * @author  PC Admin
     */
    class GuiPanel extends JPanel {
        private Controller controller; // this will tie things together
    
    
        // pass a reference to the Controller in the GUI constructor
        GuiPanel(Controller controller) {
            this.controller = controller;
    
            JButton readFileBtn = new JButton("Read File");
            readFileBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    readFileBtnActionPerformed();
                }
            });
            JButton writeFileBtn = new JButton("Write File");
            writeFileBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    writeFileBtnActionPerformed();
                }
            });
            
           JPanel graph1panel=new JPanel();//create a JPanel as a container for the graph
           graph1panel.setName("graph1 panel"); // NOI18N
            MatrixToGraph graph1=new MatrixToGraph();//instance of graph drawing class which takes as input a 2 dimensional array
            graph1 = new MatrixToGraph();
           graph1.matixToGr(edges);
            graph1panel.add(graph1);//add the
    
    
    
            add(graph1panel);
            add(readFileBtn);
            add(writeFileBtn);
        }
    
        // call the Controller methods in the button's actionPerformed methods
        private void writeFileBtnActionPerformed() {
            if (controller != null) {
                controller.writeFileAction();
            }
        }
    
        // call the Controller methods in the button's actionPerformed methods
        private void readFileBtnActionPerformed() {
            if (controller != null) {
                controller.readFileAction();
            }
    
    
    
        }
    }
    On the MatrixToGraph class i have a method which takes input the read file matrix. The method is called matixToGr(double[][] edges).
    At the end of this method I have created a jPanel which gets the graph added to it.
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package fubarable;
    
    /**
     *
     * @author  PC Admin
     */
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ItemEvent;
    import java.lang.reflect.InvocationTargetException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import javax.swing.JFrame;
    
    
    import org.apache.commons.collections15.Factory;
    import cern.colt.matrix.DoubleMatrix2D;
    import cern.colt.matrix.impl.SparseDoubleMatrix2D;
    import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
    import edu.uci.ics.jung.graph.Graph;
    import edu.uci.ics.jung.graph.SparseGraph;
    import edu.uci.ics.jung.graph.SparseMultigraph;
    import edu.uci.ics.jung.graph.DirectedGraph;
    import edu.uci.ics.jung.graph.DirectedSparseGraph;
    import edu.uci.ics.jung.graph.DirectedOrderedSparseMultigraph;
    import edu.uci.ics.jung.graph.UndirectedGraph;
    import edu.uci.ics.jung.graph.UndirectedSparseGraph;
    import edu.uci.ics.jung.graph.UndirectedOrderedSparseMultigraph;
    import edu.uci.ics.jung.graph.UndirectedSparseMultigraph;
    import edu.uci.ics.jung.algorithms.matrix.GraphMatrixOperations;
    import edu.uci.ics.jung.algorithms.layout.AbstractLayout;
    import edu.uci.ics.jung.algorithms.layout.BalloonLayout;
    import edu.uci.ics.jung.algorithms.layout.FRLayout;
    import edu.uci.ics.jung.algorithms.layout.ISOMLayout;
    import edu.uci.ics.jung.algorithms.layout.KKLayout;
    import edu.uci.ics.jung.algorithms.layout.Layout;
    import edu.uci.ics.jung.algorithms.layout.CircleLayout;
    import edu.uci.ics.jung.algorithms.layout.SpringLayout;
    import edu.uci.ics.jung.visualization.decorators.EdgeShape;
    import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
    import edu.uci.ics.jung.visualization.*;
    import edu.uci.ics.jung.visualization.decorators.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemListener;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class MatrixToGraph extends JPanel implements ActionListener, ItemListener {
    
        public void matixToGr(double[][] edges) {
    
    
    
            Map<String, Number> weights = new HashMap<String, Number>();
    
            Factory<Graph<String, String>> graphFactory = new Factory<Graph<String, String>>() {
    
                public Graph<String, String> create() {
    
                    return new SparseGraph<String, String>();
    
                }
            };
            Factory<DirectedGraph<String, String>> directedGraphFactory = new Factory<DirectedGraph<String, String>>() {
    
                //public DirectedOrderedSparseMultigraph<String, String> create() {
                public DirectedOrderedSparseMultigraph<String, String> create() {
                    return new DirectedOrderedSparseMultigraph<String, String>();
                    //	return new DirectedOrderedSparseMultigraph<String, String>();
    
                }
            };
    
            Factory<UndirectedGraph<String, String>> undirectedGraphFactory = new Factory<UndirectedGraph<String, String>>() {
    
                public UndirectedOrderedSparseMultigraph<String, String> create() {
                    return new UndirectedOrderedSparseMultigraph<String, String>();
                }
            };
    
    
            Factory<String> vertexFactory = new Factory<String>() {
    
                int n = 0;
    
                public String create() {
    
                    return "V" + n++;
    
                }
            };
    
            Factory<String> edgeFactory = new Factory<String>() {
    
                int i = 0;
    
                public String create() {
    
                    return "E" + i++;
    
                }
            };
            //change 2D array to DoubleMatrix2D
            DoubleMatrix2D m = new SparseDoubleMatrix2D(edges);
            //method to build graph from matrix
            Graph<String, String> g = GraphMatrixOperations.<String, String>matrixToGraph(m, undirectedGraphFactory, vertexFactory, edgeFactory);
    
            for (String anEdge : weights.keySet()) {
    
                double aWeight = (Double) weights.get(anEdge);
    
                System.out.println(anEdge + " " + aWeight);
    
            }
            Layout<String, String> layout = new CircleLayout(g);
    
            layout.setSize(new Dimension(300, 300));
    
            BasicVisualizationServer<String, String> vv = new BasicVisualizationServer<String, String>(
                    layout);
    
            vv.setPreferredSize(new Dimension(320, 320));
    
            //vv.getRenderContext().setEdgeLabelTransformer(nEdgeStringer);
    
            vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    
            vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line());
    
    //build panel to hold the graph
    
            JPanel graphPanel = new JPanel();
    
            graphPanel.setPreferredSize(new Dimension(320, 320));
            graphPanel.add(vv);//vv is the graph being built by the method.
            JLabel graphLabel1 = new JLabel("First Graph");
            graphPanel.add(graphLabel1);
            add(graphPanel);
    
        }//end main
    
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public void itemStateChanged(ItemEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
    Could you please help me solve this issue I am having. Do I add the graph to the readFileAction() method already in the controller or how would you suggest I go about this.

    Thanks in advance for your help,
    Jetnor.

Similar Threads

  1. [SOLVED] jfilechooser for saving a file....?
    By prabhurangan in forum AWT / Swing
    Replies: 10
    Last Post: 10-06-2013, 11:17 PM
  2. [JFileChooser] File name to list
    By Che999po in forum AWT / Swing
    Replies: 8
    Last Post: 07-30-2010, 11:09 PM
  3. Replies: 1
    Last Post: 04-23-2010, 10:27 PM
  4. Replies: 8
    Last Post: 01-21-2010, 08:16 AM
  5. Specifying absolute path in web.xml
    By Felissa in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 07-05-2007, 07:56 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •