多个java类..如何访问表单事件



好的,这是独家新闻。我有一个应用程序,它使用表单和.java文件,允许用户选择一个目录,在一个目录中查找所有照片,将所有照片转换为字节数据,并将数据插入SQL数据库。我使用过:

一个名为Photouploader 的主文件

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");
    }
    }
}

我所有的表单数据都在名为NewJFrame:的类中

    /*
 * 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                   
}

FileParser类完成了解析和准备将数据发送到SQL类的所有提升。文件解析器是:

    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)
                    );
        }
    }
}

问题是我在NewJframe类中有一个标记为Upload的按钮。与按钮按下相关的此按钮/事件不知道照片上传器主功能中运行的已初始化的文件解析器(fileParser fp = new fileParser();)类。我想要的功能是:当按下上传按钮使事件分流回main时,fp.runSQL();请注意未定义fileparser.runSQL。请帮忙。我可以用监听器将数据发送回main吗?还是应该使用接口?还是头等舱?谢谢Scorliss

您可以尝试在main中构造文件解析器对象,然后在创建时将其作为参数传递给表单类的构造函数。这将允许main和form类访问同一个文件解析器对象。

另一种选择是将公共方法添加到执行文件解析操作的主类中。然后,您可以在main中构造一个文件解析器对象,并在需要使用文件解析器对象时让form类调用main的方法。

相关内容

  • 没有找到相关文章

最新更新