-1

我无法让 Java Swing 进度监视器工作。下面的脚本转换所选目录中的所有文件。循环期间从不显示进度条窗口。可能我必须为 ProgressMonitorInputStream 提供更多提示,例如最大值和最小值。我无法单独解决这个问题,并将感谢任何帮助。

public class csvtoxls {

    public static void main() throws IOException {
//here you enter the path to your directory.
//for example: Path workDir = Paths.get("C:\\Users\\Kamil\Desktop\\csvtoxlspython\\Nowy folder (2)")
        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        jfc.setDialogTitle("Wybierz folder do konwersji: ");
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jfc.setAcceptAllFileFilterUsed(false);
        int returnValue = jfc.showSaveDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            if (jfc.getSelectedFile().isDirectory()) {
                System.out.println("You selected the directory: " + jfc.getSelectedFile());

String z;
    //@SuppressWarnings("deprecation")
    //Path workDir = jfc.getCurrentDirectory().toPath();
    //Path workDir = FileSystems.getDefault().getPath(jfc.getCurrentDirectory());
    Path workDir = Paths.get(gui.pickPath(jfc));
    System.out.println(workDir);

//the if checks whether the directory truly exists
    if (!Files.notExists(workDir )) {;

//this part stores all files withn the directory in a list
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(workDir )) {

            for (Path path : directoryStream) {



                @SuppressWarnings("deprecation")
                    ArrayList<ArrayList<String>> allRowAndColData = null;
                    ArrayList<String> oneRowData = null;
                    Path fName = workDir;
                    String currentLine;
                    FileInputStream fis = new FileInputStream(path.toString());
                    DataInputStream myInput = new DataInputStream(fis);

                    ProgressMonitorInputStream pm = new ProgressMonitorInputStream(null ,"Reading the big file", fis);


                    int c;
                    while((c=pm.read()) != -1) {



                        int i = 0;
                        allRowAndColData = new ArrayList<ArrayList<String>>();
                        while ((currentLine = myInput.readLine()) != null) {
                            oneRowData = new ArrayList<String>();
                            String oneRowArray[] = currentLine.split(";");
                            for (int j = 0; j < oneRowArray.length; j++) {
                                oneRowData.add(oneRowArray[j]);
                            }
                            allRowAndColData.add(oneRowData);
                            System.out.println();
                            i++;


                    }

                 try {

                     HSSFWorkbook workBook = new HSSFWorkbook();
                     HSSFSheet sheet = workBook.createSheet("sheet1");
                     for (int i1 = 0; i1 < allRowAndColData.size(); i1++) {
                       ArrayList<?> ardata = (ArrayList<?>) allRowAndColData.get(i1);
                       HSSFRow row = sheet.createRow((short) 0 + i1);
                       for (int k = 0; k < ardata.size(); k++) {
                            System.out.print(ardata.get(k));
                            HSSFCell cell = row.createCell((short) k);
                            cell.setCellValue(ardata.get(k).toString());


                       }
                       System.out.println();

                     }

                // Write the output to a file
                z = path.toString();
                z = z = z.substring(0, z.lastIndexOf('.'));
                FileOutputStream fileOutputStream = new FileOutputStream(z + ".xls");
                workBook.write(fileOutputStream);
                fileOutputStream.close();

            }

        catch (IOException e) {
            System.out.println(e.getMessage());
        } 

        finally {

        // ... cleanup that will execute whether or not an error occurred ...
        }

                    }
    }
    }
}
}
        }
    }
}
4

1 回答 1

1

假设您的实际代码正常工作,并且如如何使用进度条中所述,ProgressMonitor使用的 by ProgressMonitorInputStream延迟后显示,默认为 500 毫秒。如果您的工作单元足够短,对话框可能不会出现,但您可以根据需要缩短延迟:

pm.getProgressMonitor().setMillisToPopup(1);

图片

在下面的示例中,

  • SwingWorker在后台处理文件。

  • 短暂的延迟和冗长的文件使对话框按预期显示。

  • try-with-resources语句确保每个资源在语句结束时关闭。

代码,改编自这个答案

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingWorker;

/**
 * @see https://stackoverflow.com/a/46019237/230513
 * @see https://stackoverflow.com/a/26394738/230513
 */
public class ProgressBarDemo extends JFrame {

    private JButton button;

    ProgressBarDemo() {
        button = new JButton("Click me!");
        ButtonActionListener bal = new ButtonActionListener();
        button.addActionListener(bal);
        this.getContentPane().add(button);
    }

    public void go() {
        this.setLocationRelativeTo(null);
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    private void processFile() {
        File file = new File("/usr/share/dict/words");
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis);) {
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                this, "Reading " + file.getAbsolutePath(), bis);
            pmis.getProgressMonitor().setMillisToPopup(1);
            int i = 0;
            while ((i = pmis.read()) != -1) {
                System.out.print((char) i);
            }
            pmis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ButtonActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            button.setEnabled(false);
            SwingWorker worker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    processFile();
                    return null;
                }

                @Override
                protected void done() {
                    button.setEnabled(true);
                }
            };
            worker.execute();
        }
    }

    public static void main(String[] args) {
        ProgressBarDemo demo = new ProgressBarDemo();
        demo.go();
    }
}
于 2017-09-03T00:09:18.697 回答