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: Button event handler from another class

  1. #1
    Junior Member
    Join Date
    Jul 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Button event handler from another class

    Hi All,
    First off my name is scorliss and I am new to this forum.
    I have been tasked to create an application that would allow users to upload photos into a database.
    I have chooses to use java via the net beans IDE.
    I have created 4.java files in one package.
    These files are:
    Photouploader.java(has main in it)
    GUI.java (has JForm and list boxes and buttons)
    Sqlrunner.java (does all the dB work)
    And Filer.java (does all file io/conversions).

    In the photouploader file I have created 2 objects:
    GUI mainform = new GUI();
    And Filer fileworker = new Filer();

    For the most part the main function in photouploader had been the point where these 2 objects have been talking.
    I'm now at the point where I need to respond to a button press named(upload) that will initialize the process of inserting the data into the SQL database via the Sqlrunner and the Filer objects.
    When someone presses the button in mainform can I have a listener in the main class of photouploader so that I can call a method from fileworker?
    package photouploader;
    import javax.swing.*;
    import java.io.*;
     
    /**
     *
     * @author 10339
     */
    public class PhotoUploader{
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = j.showOpenDialog(null);
     
     
        if(returnVal == javax.swing.JFileChooser.APPROVE_OPTION){
            File dir = j.getSelectedFile();
            File[] matches = dir.listFiles(new FilenameFilter()
            {
                public boolean accept(File dir,String name)
                {
     
                   return name.endsWith(".png")||name.endsWith(".jpg");
                }
     
            });
     
     
            if(matches.length==0){
                JOptionPane.showMessageDialog(null,"No picture files have been "
                        + "found.");
            }
            else{
                fileParser fp = new fileParser();       //create new fileparser
                fp.setFiles(matches);                   //send in all found files
                fp.setFilenames();                      //convert files to names
     
                NewJFrame JP = new NewJFrame();             //create new form
                JP.setVisible(true);             
     
                //update lists on the form
                JP.update_Upload_list(fp.getgoodFilenames());   
                JP.update_DNUpload_list(fp.getbadFilenames());
     
     
            }
     
     
        }
        else{
            JOptionPane.showMessageDialog(null,"you have not chosen "
                    + "a valid directory");
        }
        }
    }

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package photouploader;
    import javax.swing.*;
    import java.util.*;
    /**
     *
     * @author 10339
     */
    public class NewJFrame extends javax.swing.JFrame {
     
        /**
         * Creates new form NewJFrame
         */
        public NewJFrame() {
            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() {
     
            Upload_Button = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            FilesToUpload = new javax.swing.JList();
            jScrollPane2 = new javax.swing.JScrollPane();
            DNUpload = new javax.swing.JList();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            Upload_Button.setText("Upload");
            Upload_Button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    Upload_ButtonActionPerformed(evt);
                }
            });
     
            jScrollPane1.setViewportView(FilesToUpload);
     
            jScrollPane2.setViewportView(DNUpload);
     
            jLabel1.setText("Files to Upload");
     
            jLabel2.setText("Files that will not be uploaded");
            jLabel2.setToolTipText("");
     
            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)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(Upload_Button)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                                .addComponent(jScrollPane2)))
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(5, 5, 5)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(Upload_Button)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void Upload_ButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:
        }                                             
     
        public void update_Upload_list(ArrayList goodfiles)
        {
            DefaultListModel model1 = new DefaultListModel();
            for(int i=0;i<goodfiles.size();i++){
                model1.addElement(goodfiles.get(i));
            }
            FilesToUpload.setModel(model1);
     
        }
        public void update_DNUpload_list(ArrayList badfiles)
        {
            DefaultListModel model1 = new DefaultListModel();
            for(int i=0;i<badfiles.size();i++){
                model1.addElement(badfiles.get(i));
            }
            DNUpload.setModel(model1);
     
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JList DNUpload;
        private javax.swing.JList FilesToUpload;
        private javax.swing.JButton Upload_Button;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        // End of variables declaration                   
    }

    package photouploader;
    import java.nio.*;
    import java.io.*;
    import java.util.*;
     
    /**
     * Compiles July 5th 2013
     * @author Shawn Corliss
     * Company: City of Lethbridge Fire Department
     * This is the fileParser Class
     */
    public class fileParser {
        /*var Decleration*/
        private File dir;                                   //Directory
        private File [] allFiles;                           //Holds all files with D
        private ArrayList goodfilenames = new ArrayList();  //Filenames
        private ArrayList badfilenames = new ArrayList();   //Filenames
        private ArrayList goodfiles = new ArrayList();      //Files with Dir
        private ArrayList badfiles = new ArrayList();       //Files with Dir
     
        /*Accessor Methods*/
        public File getDir(){               
            return dir;                     //Reurun Direcotry
        }   
        public void setDir(File directory){
            dir=directory;                  //Set Directory
        }
        public File[] getFiles(){
            return allFiles;                //Return all Files in array 
        }
        public ArrayList getgoodFilenames(){
            return goodfilenames ;          //Return Arrylist of files >=39
        }
        public ArrayList getbadFilenames(){
            return badfilenames ;           //Return Arrylist of files <=40
        }
        /* This funcition gets all the files found in the matching process
         * The matches are then cloned.
         * The length is checked and if +39 then files are placed in bad arraylist 
         * if smaller then 40 then they are placed in the good file arraylist
         */
        public void setFiles(File [] matches){
            allFiles=matches.clone();
            for (int a=0;a<matches.length;a++){
                if(matches[a].toString().substring
                        (matches[a].toString().lastIndexOf("\\")+1
                        ).length()<40){
                    goodfiles.add(matches[a]);
                }
                else{
                    badfiles.add(matches[a]);
                }
            }
        }
        //calls setgood and setbad filename functions
        public void setFilenames(){
            setgoodFilenames();
            setbadFilenames();
        }
     
        /*This function will convert the file path into a file name
         * by parsing out the string to the right of the last found "\"
         * used to push good file names to the list box and for conversion to bytes.
         */
     
        public void setgoodFilenames(){
            for(int i=0;i<goodfiles.size();i++){ //for each item in the goodfiles
                goodfilenames.add(
                        goodfiles.get(i).toString().substring(
                        goodfiles.get(i).toString().lastIndexOf("\\")+1)
                                );
            }
        }
     
          /*This function will convert the file path into a file name
         * by parsing out the string to the right of the last found "\"
         * used to push bad file names to the list box.
         */
        public void setbadFilenames(){
            for(int i=0;i<badfiles.size();i++){ //for each item in the badfiles
                badfilenames.add(
                        badfiles.get(i).toString().substring(
                        badfiles.get(i).toString().lastIndexOf("\\")+1)
                        );
            }
        }
    }
    Thanks all,
    Scorliss
    Last edited by Scorliss; July 8th, 2013 at 01:08 AM. Reason: ADD Cofr


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,146
    My Mood
    Mellow
    Thanks
    187
    Thanked 660 Times in 647 Posts

    Default Re: Button event handler from another class

    I'm not sure I followed correctly, but you might consider a Controller object (from the MVC design pattern) to pass the mainform object:

    PhotoController photoController = new PhotoController( mainform );

    and then use photoController to respond to actions that occur on the GUI (or View).

  3. #3
    Junior Member
    Join Date
    Jul 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button event handler from another class

    Quote Originally Posted by GregBrannon View Post
    I'm not sure I followed correctly, but you might consider a Controller object (from the MVC design pattern) to pass the mainform object:

    PhotoController photoController = new PhotoController( mainform );

    and then use photoController to respond to actions that occur on the GUI (or View).
    I'm just not sure how to use the photo controller to respond to the actions that occur on the GUI. As the photo controller isn't the jform. I have a Jerome defined in the GUI class and that class has been instantiated in the photo controller as "main from".

Similar Threads

  1. Event Handler For a JTextField
    By JamesdTurnham in forum What's Wrong With My Code?
    Replies: 8
    Last Post: June 17th, 2013, 06:16 PM
  2. JButton event handler
    By gkelly642 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2013, 09:01 PM
  3. Separate Event Handler Class
    By beer-in-box in forum AWT / Java Swing
    Replies: 2
    Last Post: April 1st, 2013, 09:19 AM
  4. Replies: 0
    Last Post: June 19th, 2012, 12:58 PM
  5. JButton event handler
    By Jsri in forum AWT / Java Swing
    Replies: 1
    Last Post: October 25th, 2011, 07:02 AM

Tags for this Thread