创建GUI以编辑多个文档

时间:2014-10-29 06:50:04

标签: java user-interface docx4j

我正在处理涉及编辑多个docx文件的个人项目。目前,我正致力于创建一个程序,允许我选择多个文件并一次编辑所有文件(所有文档都采用相同的格式,因此所需的更改是相同的)。无论如何,我发现一个GUI似乎非常适合我的需求:

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

我已编辑过,并会根据自己的口味编辑更多。 我目前的代码是:

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

代码目前产生了这个:

(我没有发布图片的声誉:P) http://imgur.com/s7rEGxu

我的目标是在用户单击“确定”时对底部区域中选择的所有文件进行编辑(此时单击“确定”只需使用docx4j创建一个word文档,所以如果您正在寻找把它放到你的IDE中,最好注释掉测试方法和ActionListener的一部分(与它有关)。

无论如何,我的问题归结为......

如何在此底部区域中选择多个文件并让“确定”按钮对其进行操作?

我想编写一个方法,当我按下OK按钮时将为每个文件调用,但我不确定如何将这些文件移入该区域后使用。

谢谢你的时间!

P.S。 (我也试图移除右侧的控制台,我无法弄清楚如何在不打破整个窗口的情况下摆脱它,所以有一些指示会受到赞赏,尽管我确定我睡了几个小时后才能得到它。谢谢!)

0 个答案:

没有答案