正在处理FTP请求时,JButton Text未更新

时间:2015-09-15 09:23:04

标签: java swing concurrency ftp event-dispatch-thread

我有这个类,并且发现我试图编辑文本以反映下载文件的当前状态的JButton在FTPclient断开之前不会更新。 由于我不确定导致问题的原因,我将添加围绕需要发生的整个主类,我还使用播放声音的方法对其进行调试,每当我尝试更新JButton的文本时都会触发。测试时似乎工作正常。

public class Main {

    public static JButton btnNewButton = null;

    private JFrame frame;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main window = new Main();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Main() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {


        frame = new JFrame();
        frame.setTitle("FTP Request");
        BorderLayout borderLayout = (BorderLayout) frame.getContentPane()
                .getLayout();
        borderLayout.setVgap(19);
        frame.getContentPane().setBackground(new Color(51, 51, 102));
        frame.setBounds(500, 500, 616, 413);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        // frame.setUndecorated(true);
        // frame.setAlwaysOnTop(true);

        btnNewButton = new JButton("EXIT");
        btnNewButton.setFont(new Font("Impact", Font.BOLD, 40));
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                btnNewButton.setText("Exitng...");
                System.exit(0);
            }
        });
        frame.getContentPane().add(btnNewButton, BorderLayout.SOUTH);

        final JLabel lblStatus = new JLabel(new ImageIcon(
                Main.class.getResource("/com/daniel/status1.png")));
        frame.getContentPane().add(lblStatus, BorderLayout.EAST);

        lblStatus.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent arg0) {
                System.out.println("CLICKED");
                btnNewButton.setText("CLIEKCED");

                playSound("1");
                String server = "f12-preview.royalwebhosting.net";
                int port = 21;
                String user = "1951435";
                String pass = "bgscoffee1";

                FTPClient ftpClient = new FTPClient();

                try {
                    // connect and login to the server
                    ftpClient.connect(server, port);
                    ftpClient.login(user, pass);

                    // use local passive mode to pass firewall
                    ftpClient.enterLocalPassiveMode();
                    playSound("2");
                    System.out.println("Connected");
                    btnNewButton.setText("Connected");

                    String remoteDirPath = "";
                    String saveDirPath = new File(path).getParent().toString()
                            + "/Download";

                    FTPUtil.downloadDirectory(ftpClient, remoteDirPath, "",
                            saveDirPath);

                    // log out and disconnect from the server
                    ftpClient.logout();
                    ftpClient.disconnect();
                    playSound("3");
                    System.out.println("Disconnected");
                    btnNewButton.setText("Disconnected");
                } catch (IOException ex) {

                    System.out.println("Error: " + ex.getMessage());
                    btnNewButton.setText("Error: " + ex.getMessage());
                    playSound("error");
                    ex.printStackTrace();
                }

            }

        });

    }

    public static synchronized void playSound(final String url) {
        new Thread(new Runnable() {
            // The wrapper thread is unnecessary, unless it blocks on the
            // Clip finishing; see comments.

            public void run() {
                try {
                    Clip clip = AudioSystem.getClip();
                    AudioInputStream inputStream = AudioSystem.getAudioInputStream(Main.class
                            .getResource("/com/daniel/" + url + ".wav"));
                    clip.open(inputStream);
                    clip.start();
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
            }
        }).start();
    }

}

仅供参考,我的FTPUtils课就在这里。

public class FTPUtil {

    /**
     * Download a whole directory from a FTP server.
     * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
     * @param parentDir Path of the parent directory of the current directory being
     * downloaded.
     * @param currentDir Path of the current directory being downloaded.
     * @param saveDir path of directory where the whole remote directory will be
     * downloaded and saved.
     * @throws IOException if any network or IO error occurred.
     */
    public static void downloadDirectory(FTPClient ftpClient, String parentDir,
            String currentDir, String saveDir) throws IOException {
        String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }

        FTPFile[] subFiles = ftpClient.listFiles(dirToList);

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    // skip parent directory and the directory itself
                    continue;
                }
                String filePath = parentDir + "/" + currentDir + "/"
                        + currentFileName;
                if (currentDir.equals("")) {
                    filePath = parentDir + "/" + currentFileName;
                }

                String newDirPath = saveDir + parentDir + File.separator
                        + currentDir + File.separator + currentFileName;
                if (currentDir.equals("")) {
                    newDirPath = saveDir + parentDir + File.separator
                              + currentFileName;
                }

                if (aFile.isDirectory()) {
                    // create the directory in saveDir
                    File newDir = new File(newDirPath);
                    boolean created = newDir.mkdirs();
                    if (created) {
                        System.out.println("CREATED the directory" + newDirPath);
                        Main.btnNewButton.setText("CREATED the directory: " + newDirPath);
                    } else {
                        Main.btnNewButton.setText("COULD NOT create the directory: " + newDirPath);
                    }

                    // download the sub directory
                    downloadDirectory(ftpClient, dirToList, currentFileName,
                            saveDir);
                } else {
                    // download the file
                    boolean success = downloadSingleFile(ftpClient, filePath,
                            newDirPath);
                    if (success) {
                        System.out.println("Downloaded: " + filePath);
                        Main.btnNewButton.setText("DOWNLOADED the file: " + filePath);
                    } else {
                        System.out.println("FAIL DOWNLOAD: " + filePath);
                        Main.btnNewButton.setText("COULD NOT download the file: "
                                + filePath);
                    }
                }
            }
        }
    }
    /**t
     * Download a single file from the FTP server
     * @param ftpClient an instance of org.apache.commons.net.ftp.FTPClient class.
     * @param remoteFilePath path of the file on the server
     * @param savePath path of directory where the file will be stored
     * @return true if the file was downloaded successfully, false otherwise
     * @throws IOException if any network or IO error occurred.
     */
    public static boolean downloadSingleFile(FTPClient ftpClient,
            String remoteFilePath, String savePath) throws IOException {
        File downloadFile = new File(savePath);

        File parentDir = downloadFile.getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdir();
        }

        OutputStream outputStream = new BufferedOutputStream(
                new FileOutputStream(downloadFile));
        try {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            return ftpClient.retrieveFile(remoteFilePath, outputStream);
        } catch (IOException ex) {
            Main.btnNewButton.setText("ERROR " + ex.toString());
            throw ex;
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

0 个答案:

没有答案