0

I'm working on a personal project which involves editing multiple docx files. Currently, I'm working on creating a program which will allow me to select multiple files and edit them all at once (all documents will be in the same format, so changes needed are the same). Anyways, I found a GUI that seemed very well suited to my needs here:

Drag'n drop files from the OS to Java application (Swing)

which I have edited, and will edit a bit more to suit my taste in the future. My current code is this:

import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import java.util.List;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class ConsolidatorDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = -4487732343062917781L;
    JFileChooser fc;
    JButton clear;
    JButton ok;
    JTextArea console;

    JList dropZone;
    DefaultListModel listModel;
    JSplitPane childSplitPane, parentSplitPane;
    PrintStream ps;

    public ConsolidatorDemo() {
        super(new BorderLayout());

        fc = new JFileChooser();;
        fc.setMultiSelectionEnabled(true);
        fc.setDragEnabled(true);
        fc.setControlButtonsAreShown(false);
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);


        JPanel fcPanel = new JPanel(new BorderLayout());
        fcPanel.add(fc, BorderLayout.CENTER);

        clear = new JButton("Clear All");
        clear.addActionListener(this);
        JPanel buttonPanel = new JPanel(new BorderLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        buttonPanel.add(clear, BorderLayout.LINE_END);

        ok = new JButton("OK");
        ok.addActionListener(this);
        buttonPanel.add(ok, BorderLayout.WEST);

        JPanel leftUpperPanel = new JPanel(new BorderLayout());
        leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        leftUpperPanel.add(fcPanel, BorderLayout.CENTER);
        leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);

        JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
        leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        listModel = new DefaultListModel();
        dropZone = new JList(listModel);
        dropZone.setCellRenderer(new FileCellRenderer());
        dropZone.setTransferHandler(new ListTransferHandler(dropZone));
        dropZone.setDragEnabled(true);
        dropZone.setDropMode(javax.swing.DropMode.INSERT);
        dropZone.setBorder(new TitledBorder("Selected files/folders"));
        leftLowerPanel.setViewportView(new JScrollPane(dropZone));

        childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                        leftUpperPanel, leftLowerPanel);
        childSplitPane.setDividerLocation(400);
        childSplitPane.setPreferredSize(new Dimension(480, 650));

        console = new JTextArea();
        console.setColumns(40);
        console.setLineWrap(true);
        console.setBorder(new TitledBorder("Console"));

        parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                         childSplitPane, console);
        parentSplitPane.setDividerLocation(480);
        parentSplitPane.setPreferredSize(new Dimension(800, 650));

        add(parentSplitPane, BorderLayout.CENTER);
    }

    public void setDefaultButton() {
        getRootPane().setDefaultButton(ok);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == clear) {
            listModel.clear();
        }
        if(e.getSource() == ok) {
            try {
                createWordDocument();
            } catch(Exception ef) {
                System.out.println("Something is wrong!");
            }
        }
    }

    private static void createWordDocument() throws Exception {
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
        wordMLPackage.getMainDocumentPart().addStyledParagraphOfText("Title", "test");
        wordMLPackage.getMainDocumentPart().addParagraphOfText("from docx4j!");

        // Now save it
        wordMLPackage.save(new java.io.File(System.getProperty("user.dir") +
                                                               "/test.docx"));
    }

    /**
     * Create the GUI and show it. For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);
        try {
               //UIManager.setLookAndFeel(
               //    "de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");

            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Create and set up the window.
        JFrame frame = new JFrame("Consolidator!");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        //Create and set up the menu bar and content pane.
        ConsolidatorDemo demo = new ConsolidatorDemo();
        demo.setOpaque(true); //content panes must be opaque
        frame.setContentPane(demo);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        demo.setDefaultButton();
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

class FileCellRenderer extends DefaultListCellRenderer {

    public Component getListCellRendererComponent(JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {

        Component c = super.getListCellRendererComponent(
            list,value,index,isSelected,cellHasFocus);

        if (c instanceof JLabel && value instanceof File) {
            JLabel l = (JLabel)c;
            File f = (File)value;
            l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
            l.setText(f.getName());
            l.setToolTipText(f.getAbsolutePath());
        }

        return c;
    }
}

class ListTransferHandler extends TransferHandler {

    private JList list;

    ListTransferHandler(JList list) {
        this.list = list;
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        // we only import FileList
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            return false;
        }
        return true;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        if (!info.isDrop()) {
            return false;
        }

        // Check for FileList flavor
        if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            displayDropLocation("List doesn't accept a drop of this type.");
            return false;
        }

        // Get the fileList that is being dropped.
        Transferable t = info.getTransferable();
        List<File> data;
        try {
            data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
        } catch (Exception e) { return false; }
        DefaultListModel model = (DefaultListModel) list.getModel();
        for (Object file : data) {
            model.addElement((File)file);
        }
        return true;
    }

    private void displayDropLocation(String string) {
        System.out.println(string);
    }
}

The code currently produces this:

(I don't have the reputation to post an image :P) https://i.stack.imgur.com/oyS4O.jpg

My goal is to make it so all of the files selected in the bottom area will then be edited when the user clicks OK (At the moment clicking OK simply creates a word document using docx4j, so if you're looking to put this into your IDE it would probably be best to comment out the test method and part of the ActionListener that have to do with it).

Anyways, my question boils down to...

How do I take a number of files selected in this bottom area and have the OK button do stuff to them?

I want to write a method which will be called for each file when I press the OK button, but I'm not sure how to use the files once they've been moved into the area.

Thanks for your time!

P.S. (I was also trying to remove the console on the right side and I couldn't figure out how to get rid of it without breaking the entire window, so a few pointers there would be appreciated, although I'm sure I'll get it after a few hours of sleep. Thanks!)

Community
  • 1
  • 1
Ryan
  • 47
  • 1
  • 1
  • 6
  • Start by checking out [How to Use Lists](http://docs.oracle.com/javase/tutorial/uiswing/components/list.html), then take a look at [`JList#getSelectedIndices`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedIndices()), [`JList#getSelectedValues`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedValues()) or [`Jlist#getSelectedValuesList`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedValuesList()) if you're using Java 7+ – MadProgrammer Oct 29 '14 at 06:54
  • Thanks! My current idea is to use a for loop through listModel.size() and have something like path.add(listModel.getElement().toPath()); with an arraylist of Paths. From there I would be able to do what I wanted I think, but at the moment I'm getting an error for getElement "is undefined type for the type DefaultListModel" – Ryan Oct 29 '14 at 12:36

0 Answers0