Swing Worker不处理更新

时间:2015-01-13 05:22:30

标签: java swing swingworker

试图让zip文件管理器更新JTextArea但由于某种原因,process()永远不会被执行。

修改

以下是建议的整个计划:

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import net.miginfocom.swing.MigLayout;

@SuppressWarnings("serial")
public class Reader extends JFrame{

    // Sets the Window bar Title and the size of the window
    private static String windowTitle = "SRT Converter";
    private static Dimension windowSize = new Dimension(400,400);
    private JTextField txtFileIn;

    private File fileIn = null;
    private File fileOut = null;
    private JTextArea txtOutputPanel;

    public Reader() {

        JButton btnSelectArchive = new JButton("Select Archive");
        btnSelectArchive.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String path = fileOpenDialog();
                if(!path.isEmpty()){
                    fileIn = new File(path);
                    String[] tokens = path.split("\\\\");
                    StringBuilder sb = new StringBuilder();
                    for(int i = 0; i < tokens.length -1; i++)
                    {
                        sb.append(tokens[i] + "\\");
                    }
                    sb.append("Transcript.txt");
                    fileOut = new File(sb.toString());
                    txtFileIn.setText(fileIn.toString());
                }
                else {
                    String message = "You need to select an archive file (zip)";
                    JOptionPane.showMessageDialog(null, message,"No File", JOptionPane.YES_OPTION);
                }
            }
        });
        getContentPane().setLayout(new MigLayout("", "[101px,grow][71px,grow][86px,grow]", "[23px][][][][][][grow]"));
        getContentPane().add(btnSelectArchive, "cell 0 0,growx,aligny top");

        txtFileIn = new JTextField();
        getContentPane().add(txtFileIn, "cell 1 0 2 1,growx,aligny center");
        txtFileIn.setColumns(10);

        JButton btnConvert = new JButton("Convert");
        btnConvert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                readZipFile();
            }
        });
        getContentPane().add(btnConvert, "cell 0 1,growx,aligny top");

        JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, "cell 0 2 3 5,grow");

        txtOutputPanel = new JTextArea();
        scrollPane.setViewportView(txtOutputPanel);
    }

    // Read in a zip file
    private void readZipFile(){

        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                ZipFile zipFile = null;
                try {
                    zipFile = new ZipFile(fileIn);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while(entries.hasMoreElements()){
                        final ZipEntry entry = entries.nextElement();

                        writeFile("\n\n");
                        writeFile(entry.getName());
                        writeFile("\n");

                        FileWriterWorker fr = new FileWriterWorker(zipFile, entry);
                        fr.execute();

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        t.start();

    }

    /** 
     * Allows user to pick a file from a directory (base directory set when created)
     * 
     * @param fileChooser -- JFileChooser to Use
     * @param panel -- panel to tie dialogBox to
     * @return -- string with the path name
     */
    private String fileOpenDialog()
    {
        String path = null;
        JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setAcceptAllFileFilterUsed(false);
        //      fileChooser.setFileFilter(filter);

        int openFile = fileChooser.showOpenDialog(getContentPane());

        if (openFile == JFileChooser.APPROVE_OPTION)
        {
            File file = fileChooser.getSelectedFile();
            // check if file has extension
            if (file.getAbsolutePath().endsWith(".zip"))
            {
                path = file.getAbsolutePath();  // if it does just return it
            } else {
                path = file.getAbsolutePath() + ".zip";  // if it does not append it to the path
            }
        } else {
            path = "";      // set path to null if no file was selected (avoids null exception)
        }
        return path;        // return path to file
    }


    private void writeFile(String str){

        BufferedWriter bw = null;

        if(fileOut == null){
            try {
                throw new Exception("Output File Does not exist");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            bw = new BufferedWriter(new FileWriter(fileOut + "Transcript.txt", true));
            bw.write(str);
            bw.newLine();
            bw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {                       // always close the file
            if (bw != null) try {
                bw.close();
            } catch (IOException ioe2) {/* just ignore it */}
        }


    }


    /**
     *  Main program driver
     * 
     * @param args - Takes no arguments
     */
    public static void main(String[] args) {    
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    InitalizeAndShowGUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private static void InitalizeAndShowGUI(){

        // Create the main window
        Reader mWindow = new Reader();
        mWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mWindow.setTitle(windowTitle);
        mWindow.setMinimumSize(windowSize); // smallest window can get

        // Set window in center of Default Monitor Window
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice device = ge.getDefaultScreenDevice();
        Rectangle screenRect = device.getDefaultConfiguration().getBounds();
        mWindow.setLocation(screenRect.width/2 - windowSize.width/2,
                screenRect.height/2 - windowSize.height/2);

        mWindow.pack();
        mWindow.setVisible(true);
    }

    private class FileWriterWorker extends SwingWorker<Void, String>{
        private ZipFile zipFile;
        private ZipEntry entry;

        public FileWriterWorker(ZipFile zipFile, ZipEntry entry){
            this.zipFile = zipFile;
            this.entry = entry;
        }

        @Override
        protected Void doInBackground() throws Exception {

            InputStream stream = zipFile.getInputStream(entry);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = reader.readLine()) != null) {
                if(line.contains("0:") || line.isEmpty())
                    continue;

                writeFile(line);

            }
            writeFile("\n\n");
            publish(entry.getName());
            System.out.println(entry.getName());
            return null;
        }

        @Override
        protected void process(List<String> update) {
            for (String str : update) {
                txtOutputPanel.append(str + "\n");  
            }
        }
    }

}    

一切正常,输出文件创建,zip文件内容写成功。正在实现SwingWorker以更新用户关于正在读取的zip文件中的当前位置,因为zip包含大量文件并且将花费一些时间来读取和写出。我尝试在publish()调用之后放置一个系统,然后执行,但process()中的System.out.println(str)永远不会触发。除了process()方法之外,一切都有效。甚至在process()中的循环之前直接放置一个sysout,并且永远不会执行。任何的想法??不解...

EDIT2

我发布了整个示例,最后的解决方案是调用readZipFile()方法在自己的线程中读取文件,同时继续更新SwingWorker中的编写器,更新GUI运行的EDT线程。谢谢所有!

0 个答案:

没有答案
相关问题