2013-07-05 12 views
-1

好的,這是獨家新聞。我有一個應用程序使用窗體和.java文件,允許用戶選擇一個目錄,查找目錄中的所有照片,將所有照片轉換爲字節數據並將數據插入SQL數據庫。我已經使用:多個java類...如何訪問主窗體事件?

稱爲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類。 Fileparser是:

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類。與按鈕按下相關聯的按鈕/事件不知道已經初始化的文件分析器(fileParser fp = new fileParser();)類在光電裝載器主要功能中運行。我想要的功能是: 當上傳按鈕被按下時事件分流回到主fp.runSQL(); 請注意 fileparser.runSQL未定義。 請幫忙。 我可以使用監聽器將數據發送回主服務器嗎?或者我應該使用一個接口?或者是一個interclass? 感謝, Scorliss

回答

0

你可以嘗試構建文件解析器對象爲主,然後傳遞一個作爲參數傳遞給窗體類的構造函數創建時。這將允許主類和表單類訪問相同的文件分析器對象。

另一種選擇是將公共方法添加到執行文件解析操作的主類中。然後,您可以在main中構造一個文件解析器對象,並在需要使用文件解析器對象時將該窗體類調用到main的方法中。

+0

你怎麼能在一個單獨的類與你的主要功能瞭解按鈕按下事件的類的表單?我試圖讓我的GUI與我的主類和我的工作類保持在一個單獨的類中。 – scorliss