Monday, February 17, 2014

Java : Add Browse button to GUI

Add Browse button to GUI

 

 Before starting :

  1. WindowBuilder Pro - should have been added to eclipse
  2. Create a new project
  3. Inside your package  , Rt ck >New >Other>WindowBuilder-Swing Designer-(Select) Application window.
  4. Once the workspace is created , at the bottom a new tab "Design" will be created. Select that.
  5. Now in the Layout select "Spring Layout" or "Mig Layout"  - this would place the relative and child properties close .
  6. Now in  components > click JButton and click on UI panel where you want it to be placed.
  7. Now right click on the placed element and select Add>Event handler>Mouse >Mouse clicked.
  8. Once done you will be taken to the code, an Anonymous class will be created on JButton.
  9. Come back to design .
  10. In components >select JFile Chooser and place it on the panel.
  11. Once done go back to the source and find JFile Chooser code and put it inside the anonymous inner class of JButton created before.
  12. Now add JFileChoose_object.showOpenDialog(class_name.this);
  13. Now run the same

 

Code Here :

JButton btnBrowse = new JButton("Browse");
        btnBrowse.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser Filechoose=new JFileChooser();
                int retval=Filechoose.showOpenDialog(GUI2.this);

                if (retval == JFileChooser.APPROVE_OPTION) {
                    //... The user selected a file, get it, use it.
                    File file = Filechoose.getSelectedFile();
                    System.out.println(file.getPath());
                }
            }
        });

No comments:

Post a Comment