在java swt中正确使用thread和display.asyncexe

时间:2017-03-29 01:05:33

标签: java multithreading user-interface swt

我正在做一个需要线程的程序,因为它在GUI开始工作时没有响应。我使用了thread,但我不知道使用它是否正确,我也使用了display.asyncExec每个都给了我错误

这是代码

btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {


                    display.asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }

    });

错误

java.lang.NullPointerException
    at org.eclipse.wb.swt.FortryApplication$5.widgetSelected(FortryApplication.java:303)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
    at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:63)
    at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:486)

for Thread我试过这些

btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                new Thread(){
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                //                      tc1 = new threadclass();
                                //                      tc = new threadclass();
                                //                      tc1.start();
                                //                      tc.start();
                            }
                        }
                    }
                }.start();
            }
        });

错误显示:

Exception in thread "Thread-2" org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.error(Unknown Source)
    at org.eclipse.swt.widgets.Widget.checkWidget(Unknown Source)
    at org.eclipse.swt.widgets.Text.getText(Unknown Source)
    at org.eclipse.wb.swt.FortryApplication$4$1.run(FortryApplication.java:239)

编辑

完整代码:

ublic class FortryApplication implements Runnable {
    static Display display;
    static Shell shell;
    static Color color;
    private static Text txtSource;
    private static Text txtDestination;
    private static Text txtDetails;
    static DateTime dateFrom;
    static DateTime dateTo;
    Button btnSourceFile, btnSelectFolder;
    Button btnBrowseFile;
    Button btnCopyFolder;
    Button btnCopyFile;
    Button btnCancel;
    static String text = "" ;
    static String text2 = "" ;
    threadclass tc = new threadclass();
    threadclass tc1 = new threadclass();



    // pos x, pos y, width, height
    public void open() {

        Display display = Display.getDefault();
        createContents();
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    protected void createContents()
    {
        shell = new Shell();
        shell.setSize(600,530);
        shell.setText("SWT Shell Demonstration");
        shell.setLayout(new GridLayout());

        final Group grpInput = new Group(shell, SWT.NONE);
        grpInput.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        grpInput.setText("Input File");
        GridLayout gl_grpInput = new GridLayout();
        gl_grpInput.numColumns = 3;
        grpInput.setLayout(gl_grpInput);
        GridData gd_grpInput = new GridData(GridData.FILL_HORIZONTAL);
        gd_grpInput.widthHint = 419;
        gd_grpInput.verticalAlignment = SWT.CENTER;
        gd_grpInput.heightHint = 57;
        grpInput.setLayoutData(gd_grpInput);

        btnSourceFile = new Button(grpInput, SWT.PUSH);
        btnSourceFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                FileDialog fd = new FileDialog(shell, SWT.MULTI);
                //              Collection files = new ArrayList();
                String firstFile = fd.open();
                if (firstFile != null) {
                    txtSource.setText("");
                    String[] selectedFiles = fd.getFileNames();
                    File file = new File(firstFile);
                    for (int ii = 0; ii < selectedFiles.length; ii++ )
                    {
                        if (file.isFile())
                        {
                            tc.displayFiles(new String[] { file.toString()});
                        }
                        else
                            tc.displayFiles(file.list());
                    }
                }
                btnCopyFolder.setEnabled(false);
                btnCopyFile.setEnabled(true);
                btnCancel.setEnabled(true);
            }
        });
        btnSourceFile.setText("Select File");

        btnSelectFolder = new Button(grpInput, SWT.NONE);
        btnSelectFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {

                DirectoryDialog dlg = new DirectoryDialog(shell);
                dlg.setFilterPath(txtSource.getText());
                dlg.setMessage("Select a source file to transfer");
                String dir = dlg.open();
                if (dir != null) {
                    txtSource.setText(dir);
                    btnCopyFile.setEnabled(false);
                    btnCopyFolder.setEnabled(true);
                    btnCancel.setEnabled(true);
                    //                  txtDetails.setText("Progress " + "\n");
                }

            }

        });
        btnSelectFolder.setText("Select Folder");
        new Label(grpInput, SWT.NONE);

        txtSource = new Text(grpInput, SWT.BORDER);
        txtSource.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
        new Label(grpInput, SWT.NONE);

        Group grpDestnationFile = new Group(shell, SWT.NONE);
        grpDestnationFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDestnationFile.setText("Destnation File");
        grpDestnationFile.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDestnationFile = new GridLayout();
        gl_grpDestnationFile.numColumns = 2;
        grpDestnationFile.setLayout(gl_grpDestnationFile);

        btnBrowseFile = new Button(grpDestnationFile, SWT.NONE);
        btnBrowseFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {
                DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
                dialog.setFilterPath(txtDestination.getText());
                String dir = dialog.open();
                if(dir != null){
                    txtDestination.setText(dir);
                }
            }
        });
        btnBrowseFile.setText("Browse File");
        new Label(grpDestnationFile, SWT.NONE);

        txtDestination = new Text(grpDestnationFile, SWT.BORDER);
        GridData gd_txtDestination = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDestination.widthHint = 429;
        txtDestination.setLayoutData(gd_txtDestination);
        new Label(grpDestnationFile, SWT.NONE);
        Label label = new Label(grpDestnationFile, SWT.NONE);
        GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label.heightHint = -5;
        label.setLayoutData(gd_label);

        Group grpDateRange = new Group(shell, SWT.NONE);
        grpDateRange.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpDateRange = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpDateRange.heightHint = 63;
        gd_grpDateRange.widthHint = 78;
        grpDateRange.setLayoutData(gd_grpDateRange);
        grpDateRange.setText("Date Range");

        DateTime dateFrom = new DateTime(grpDateRange, SWT.BORDER);
        dateFrom.setBounds(111, 40, 122, 24);

        Label lblFrom = new Label(grpDateRange, SWT.NONE);
        lblFrom.setBounds(153, 19, 55, 15);
        lblFrom.setText("From");

        DateTime dateTo = new DateTime(grpDateRange, SWT.BORDER);
        dateTo.setBounds(352, 40, 122, 24);

        Label lblTo = new Label(grpDateRange, SWT.NONE);
        lblTo.setText("To");
        lblTo.setBounds(397, 19, 55, 15);

        Label label_1 = new Label(grpDateRange, SWT.NONE);
        label_1.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
        label_1.setBounds(293, 40, 20, 24);
        label_1.setText(":");

        Group grpDetails = new Group(shell, SWT.NONE);
        grpDetails.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        grpDetails.setText("Details");
        grpDetails.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridLayout gl_grpDetails = new GridLayout();
        gl_grpDetails.numColumns = 2;
        grpDetails.setLayout(gl_grpDetails);

        txtDetails = new Text(grpDetails, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
        GridData gd_txtDetails = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
        gd_txtDetails.widthHint = 460;
        gd_txtDetails.heightHint = 66;
        txtDetails.setLayoutData(gd_txtDetails);

        new Label(grpDetails, SWT.NONE);
        Label label_2 = new Label(grpDetails, SWT.NONE);
        GridData gd_label_2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
        gd_label_2.heightHint = -3;
        label_2.setLayoutData(gd_label_2);

        Group grpCopyOptions = new Group(shell, SWT.NONE);
        grpCopyOptions.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
        GridData gd_grpCopyOptions = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
        gd_grpCopyOptions.heightHint = 70;
        gd_grpCopyOptions.widthHint = 492;
        grpCopyOptions.setLayoutData(gd_grpCopyOptions);
        grpCopyOptions.setText("Copy Options");

        btnCopyFile = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFile.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0)
            {
                Display.getDefault().asyncExec(
                        new Runnable()
                        {
                    public void run()
                    {

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());
                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEditable(false);
                            txtDestination.setText("");

                        }else{

                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("Warning");
                                msgBox.setMessage("Invalid Path..");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                            }
                            else
                            {
                                try {
                                    tc.copyFolder1(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                                        tc1 = new threadclass();
                                                        tc = new threadclass();
                                                        tc1.start();
                                                        tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFile.setBounds(128, 23, 166, 25);
        btnCopyFile.setText("Copy File");

        btnCopyFolder = new Button(grpCopyOptions, SWT.NONE);
        btnCopyFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent arg0) {


                    Display.getDefault().asyncExec(
                    new Runnable()
                    {
                    public void run(){

                        File srcFolder = new File(txtSource.getText());
                        File destFolder = new File(txtDestination.getText());

                        if(!srcFolder.exists()){
                            MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            msgBox.setText("Information");
                            msgBox.setMessage("Directory does not exist.");
                            msgBox.open();
                            txtSource.setText("");
                            txtSource.setEnabled(false);
                            txtDestination.setText("");

                        }else{
                            if(txtDestination.getText().isEmpty())
                            {
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
                                msgBox.setText("WARNING");
                                msgBox.setMessage("Invalid Path...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);
                            }
                            else
                            {
                                try {
                                    tc.copyFolder(srcFolder,destFolder);
                                } catch (IOException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                txtDetails.append("Finished Copying.....\n");
                                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                                msgBox.setText("Information");
                                msgBox.setMessage("Done Copying...");
                                msgBox.open();
                                txtSource.setText("");
                                txtSource.setEditable(false);
                                txtDestination.setText("");
                                btnCopyFolder.setEnabled(true);
                                btnCopyFile.setEnabled(true);

                                tc1 = new threadclass();
                                tc = new threadclass();
                                tc1.start();
                                tc.start();
                            }
                        }
                    }
                });
            }
        });
        btnCopyFolder.setText("Copy Folder");
        btnCopyFolder.setBounds(300, 23, 166, 25);

        btnCancel = new Button(grpCopyOptions, SWT.NONE);
        btnCancel.setBounds(247, 54, 96, 25);
        btnCancel.setText("Cancel");
    }

    class threadclass extends Thread
    {
        public void cancel(boolean b) {

            tc.interrupt();

        }
        public void displayFiles(String[] files) {
            for (int i = 0; files != null && i < files.length; i++) {
                txtSource.append(files[i]);
                txtSource.setEditable(false);

            }
        }

        public void copyFolder(File src, File dest)
                throws IOException{
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                final String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder(srcFile, destFile);
                }
            }
            else{
                //              btnCancel.setEnabled(true);
                txtDetails.append("");
                Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                //
            }
        }
        public void copyFolder1(File src, File dest)
                throws IOException{
            //      String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
            if(src.isDirectory()){
                if (!dest.exists())
                {
                    dest.mkdir();
                    txtDetails.append("Directory created : " + dest + "\n");
                }
                String files[] = src.list();
                for (String file : files)
                {
                    File srcFile = new File(src, file);
                    File destFile = new File(dest, file);

                    //Recursive function call
                    copyFolder1(srcFile, destFile);
                }
            }
            else{
                if(dest.isDirectory())
                {
                    //                  btnCancel.setEnabled(true);
                    copyFile(src, new File (dest, src.getName()));
                    txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
                }
                else
                {
                    copyFile(src, dest);
                }
                //          }
            }
        }
        public void copyFile(File src, File dest) throws IOException
        {
            InputStream oInStream = new FileInputStream(src);
            OutputStream oOutStream = new FileOutputStream(dest);

            // Transfer bytes from in to out
            byte[] oBytes = new byte[1024];
            int nLength;
            BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
            while ((nLength = oBuffInputStream.read(oBytes)) > 0)
            {
                oOutStream.write(oBytes, 0, nLength);
            }
            oInStream.close();
            oOutStream.close();
        }
        public  void fileCopy(File sourceDir , File destDir) throws IOException{
            //    File sDir = new File(sourceDir);
            if (!sourceDir.isDirectory()){
                // throw error
            }
            //    File dDir = new File(destDir);
            if (!destDir.exists()){
                destDir.mkdir();
            }
            File[] files = sourceDir.listFiles();
            for (int i = 0; i < files.length; i++) {
                File destFile = new File(destDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "")  //remove the commas
                        .replace("[", "")   //remove the right bracket
                        .replace("]", "")
                        .replace(" ", ""));
                //  destFile.createNewFile();
                Files.copy(files[i].toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                txtDetails.append(text + " Copying " + files[i].getAbsolutePath() + "\n");
            }

        }
    }

    public static void main(String[] args) {
        try {
            FortryApplication window = new FortryApplication();
            window.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:0)

您不使用asyncExec来运行后台任务,asyncExec始终在UI线程中运行代码。

每次要执行UI操作时,都会在后台线程中使用asyncExec 必须使用后台线程执行长时间运行的任务。

因此,当您想要运行长时间运行的任务时,您可以执行以下操作:

Thread background = new Thread() {
  @Override
  public void run() {

     ... long running background code

     Display.getDefault().asyncExec(new Runnable() {
        @Override
        public void run() {
           .. code accessing user interface objects
        }
     });

     .... more code
  }
};

background.start();