com.stam.batchmove.SelectionFrame.java Source code

Java tutorial

Introduction

Here is the source code for com.stam.batchmove.SelectionFrame.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.stam.batchmove;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author StamaterisG
 */
public class SelectionFrame extends javax.swing.JFrame {

    /**
     * Creates new form Frame
     */
    public SelectionFrame() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        importFile = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        helpTxt = new javax.swing.JTextArea();
        selectSourceDirBtn = new javax.swing.JButton();
        sourceDir = new javax.swing.JTextField();
        selectFiles = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("selectionFrame"); // NOI18N
        setResizable(false);

        importFile.setText("Import File");
        importFile.setMaximumSize(new java.awt.Dimension(67, 23));
        importFile.setMinimumSize(new java.awt.Dimension(67, 23));
        importFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importFileActionPerformed(evt);
            }
        });

        helpTxt.setEditable(false);
        helpTxt.setColumns(20);
        helpTxt.setRows(5);
        helpTxt.setText(
                "Select source directory: The directory where the photos to be moved are.\n\nImport file: Import the file with the list of filenames to be moved. \nThe filenames can be with or without extensions\n\n\nFile example\n--------------\n\nphoto1.jpg\nphoto2    \nphoto3.png");
        jScrollPane1.setViewportView(helpTxt);

        selectSourceDirBtn.setText("Select source directory");
        selectSourceDirBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectSourceDirBtnActionPerformed(evt);
            }
        });

        sourceDir.setEditable(false);

        selectFiles.setText("Select Files");
        selectFiles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectFilesActionPerformed(evt);
            }
        });

        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)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(sourceDir, javax.swing.GroupLayout.DEFAULT_SIZE, 376,
                                                Short.MAX_VALUE)
                                        .addComponent(selectFiles, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(importFile, javax.swing.GroupLayout.Alignment.TRAILING,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(selectSourceDirBtn,
                                                javax.swing.GroupLayout.Alignment.TRAILING,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE))))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(selectSourceDirBtn, javax.swing.GroupLayout.DEFAULT_SIZE, 31,
                                        Short.MAX_VALUE)
                                .addComponent(sourceDir))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup().addGap(11, 11, 11).addComponent(importFile,
                                        javax.swing.GroupLayout.PREFERRED_SIZE, 39,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(selectFiles, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                        .addContainerGap()));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void importFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importFileActionPerformed
        String path = sourceDir.getText();
        if (path == null || path.trim().equals("")) {
            JOptionPane.showMessageDialog(this, "You must first select a source directory", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setDialogTitle("Choose file to import");
        int retVal = fileChooser.showOpenDialog(this);
        if (retVal == JFileChooser.APPROVE_OPTION) {
            File sourceDir = new File(path);
            File[] sourceDirFilesArr = sourceDir.listFiles();
            List<File> sourceDirFiles = Arrays.asList(sourceDirFilesArr);

            File selection = fileChooser.getSelectedFile();

            List<File> files = new ArrayList<>();
            try (BufferedReader br = new BufferedReader(new FileReader(selection))) {
                for (String line; (line = br.readLine()) != null;) {
                    if (line != null && !line.trim().equals("")) {
                        File file = BatchMoveUtils.findFileByName(sourceDirFiles, line);
                        if (file != null) {
                            files.add(file);
                        }
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            String[] columnNames = { "", "Filename", "Size", "Status" };
            Object[][] data = new Object[files.size()][4];

            int fileNo = 0;
            for (File file : files) {
                data[fileNo][0] = file.exists();
                data[fileNo][1] = file.getAbsolutePath();
                data[fileNo][2] = file.length();
                data[fileNo][3] = file.exists() ? "Found" : "Not found";

                fileNo++;
            }

            BatchMoveUtils.showFilesFrame(data, columnNames, this);
        }
    }//GEN-LAST:event_importFileActionPerformed

    private void selectSourceDirBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectSourceDirBtnActionPerformed
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setDialogTitle("Choose source directory");
        int retVal = fileChooser.showOpenDialog(this);
        if (retVal == JFileChooser.APPROVE_OPTION) {
            File selection = fileChooser.getSelectedFile();
            String selectedFolder = selection.getAbsolutePath();

            sourceDir.setText(selectedFolder);
        }
    }//GEN-LAST:event_selectSourceDirBtnActionPerformed

    private void selectFilesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectFilesActionPerformed
        String path = sourceDir.getText();
        if (path == null || path.trim().equals("")) {
            JOptionPane.showMessageDialog(this, "You must first select a source directory", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        File sourceDir = new File(path);
        File[] sourceDirFilesArr = sourceDir.listFiles();
        List<File> files = Arrays.asList(sourceDirFilesArr);

        String[] columnNames = { "", "Filename", "Size", "Type" };
        Object[][] data = new Object[files.size()][4];

        int fileNo = 0;
        for (File file : files) {
            data[fileNo][0] = false;
            data[fileNo][1] = file.getAbsolutePath();
            data[fileNo][2] = file.length();
            data[fileNo][3] = file.isFile() ? "File" : "Directory";

            fileNo++;
        }
        BatchMoveUtils.showFilesFrame(data, columnNames, this);
    }//GEN-LAST:event_selectFilesActionPerformed

    /**
     * @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(SelectionFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SelectionFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SelectionFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SelectionFrame.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 SelectionFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JTextArea helpTxt;
    private javax.swing.JButton importFile;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton selectFiles;
    private javax.swing.JButton selectSourceDirBtn;
    private javax.swing.JTextField sourceDir;
    // End of variables declaration//GEN-END:variables

    public JFileChooser getFileChooser() {
        return fileChooser;
    }
}