-1

これがスクープです。ユーザーがディレクトリを選択し、ディレクトリ内のすべての写真を検索し、すべての写真をバイトデータに変換し、データを 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 クラスに送信する準備をすべて行います。ファイルパーサーは次のとおりです。

    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();、photouploaders のメイン関数で実行されている、既に初期化されている fileparser( ) クラスに関する知識がありません。私が望む機能は次のとおりです。イベントがメインに戻るためにアップロードボタンが押されたとき fileparser.runSQL が定義されていないことに注意してください。助けてください。リスナーを使用してデータをメインに戻すことはできますか? またはインターフェイスを使用する必要がありますか?またはインタークラス?ありがとう、スコーリス

4

1 に答える 1

0

メインでファイル パーサー オブジェクトを構築し、作成時にフォーム クラスのコンストラクターにパラメーターとして渡すことができます。これにより、メイン クラスとフォーム クラスの両方が同じファイル パーサー オブジェクトにアクセスできるようになります。

もう 1 つのオプションは、ファイルの解析操作を行うパブリック メソッドをメイン クラスに追加することです。次に、main で 1 つのファイル パーサー オブジェクトを構築し、ファイル パーサー オブジェクトを使用する必要がある場合に、フォーム クラスで main のメソッドを呼び出すことができます。

于 2013-07-05T23:17:59.973 に答える