【问题标题】:How to keep application work when executing button click java执行按钮单击java时如何保持应用程序工作
【发布时间】:2016-05-08 09:52:17
【问题描述】:

当我单击检查按钮时,应用程序在处理作业时停止。

我想获得实时结果。

这是我的代码。

我用这个应用程序检查了一些雅虎帐户。

点击check的时候我想一个一个的得到结果,但是点击check的时候必须等到所有的账户都被check之后才能得到结果。

package package_1;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import package_1.ProgressBarDemo2.Task;
import javax.swing.JSeparator;
import javax.mail.AuthenticationFailedException;
import javax.mail.Session;
import javax.mail.Store;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Properties;
import javax.swing.JProgressBar;

public class EmailChecker extends SwingWorker<Void, Void>{

    private JFrame frame;
    private JTextField textField;
    public static boolean state = true;
    public Task task;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
                public void run() {

                    try {
                        EmailChecker window = new EmailChecker();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    }

    public void checkcurrent(String[] _Account,String[] _Pass,JTextArea _textArea,JTextArea _textArea_1,int _i,JProgressBar _progressBar,int _size) throws InterruptedException{

        if(_i<_size && state == true){

            Properties props = System.getProperties();
            props.setProperty("mail.debug", "false");
            props.setProperty("mail.store.protocol", "imaps");
            try {
                Session session = Session.getDefaultInstance(props, null);
                Store store = session.getStore("imaps");
                try {
                    store.connect("imap.mail.yahoo.com", _Account[_i], _Pass[_i]);
                } catch (AuthenticationFailedException e) {
                }
                if(store.isConnected() == true){
                    _textArea.setText(_Account[_i]+"/"+_Pass[_i]+ "\n" + _textArea.getText() );
                }else{

                    _textArea_1.setText(_Account[_i]+"/"+_Pass[_i] + "\n" +_textArea_1.getText());

                }
            } catch (Exception e) {
            }
            _progressBar.setValue(100);
            _i++;
            System.out.println("checked");
            checkcurrent(_Account,_Pass,_textArea,_textArea_1,_i,_progressBar,_size);
        }else{
            state = false;
        } 
    }

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

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().setBackground(Color.LIGHT_GRAY);
        frame.setBounds(100, 100, 655, 433);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JTextPane textPane = new JTextPane();
        textPane.setBounds(10, 34, 100, 140);
        frame.getContentPane().add(textPane);

        JTextPane textPane_1 = new JTextPane();
        textPane_1.setBounds(120, 34, 92, 140);
        frame.getContentPane().add(textPane_1);

        JTextPane textPane_2 = new JTextPane();
        textPane_2.setBounds(332, 34, 92, 140);
        frame.getContentPane().add(textPane_2);

        JTextPane textPane_3 = new JTextPane();
        textPane_3.setBounds(222, 34, 100, 140);
        frame.getContentPane().add(textPane_3);

        JTextPane textPane_4 = new JTextPane();
        textPane_4.setBounds(544, 34, 92, 140);
        frame.getContentPane().add(textPane_4);

        JTextPane textPane_5 = new JTextPane();
        textPane_5.setBounds(434, 34, 100, 140);
        frame.getContentPane().add(textPane_5);

        JTextArea textArea = new JTextArea();
        textArea.setToolTipText("Account Ok");
        textArea.setBounds(10, 222, 292, 154);
        frame.getContentPane().add(textArea);

        JProgressBar progressBar = new JProgressBar();
        progressBar.setMinimum(100);
        progressBar.setBounds(10, 379, 626, 16);
        frame.getContentPane().add(progressBar);

        JTextArea textArea_1 = new JTextArea();
        textArea_1.setBounds(344, 222, 292, 154);
        frame.getContentPane().add(textArea_1);

        JButton btnCheck = new JButton("Check");
        btnCheck.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    String[] Account = textPane.getText().split("\\n");
                    String[] Pass = textPane_1.getText().split("\\n");
                    //String[] Proxy = textPane_2.getText().split("\\n");
                    //String[] Port = textPane_3.getText().split("\\n");
                    //String[] Login = textPane_4.getText().split("\\n");
                    //String[] PassPrx = textPane_5.getText().split("\\n");

                    int size = Account.length;
                    int i = 0;

                    try {
                        checkcurrent(Account,Pass,textArea,textArea_1,i,progressBar,size);
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            });
        btnCheck.setLocation(280, 185);
        btnCheck.setBackground(Color.WHITE);
        btnCheck.setSize(83, 29);
        frame.getContentPane().add(btnCheck);
    }

    @Override
    protected Void doInBackground() throws Exception {
        return null;
        // TODO Auto-generated method stub
    }
}

【问题讨论】:

  • 您必须让您的应用程序异步运行,以便获得非阻塞 UI,例如,通过在新的 Thread 中运行您的 checkcurrent() 方法。这里有一个关于 Java 多线程的教程:beginnersbook.com/2013/03/multithreading-in-java
  • 感谢我是新的 Java 编码器,你能修改我的代码吗?

标签: java yahoo


【解决方案1】:

使用 AsysncTask。

AsyncTask 允许正确且轻松地使用 UI 线程。这节课 允许执行后台操作并在 UI 上发布结果 线程,而无需操作线程和/或处理程序。

AsyncTask 被设计成一个围绕 Thread 和 Handler 的辅助类 并且不构成通用线程框架。异步任务 理想情况下应用于短操作(几秒钟在 大多数。)如果您需要保持线程长时间运行, 强烈建议您使用由 java.util.concurrent 包,例如 Executor、ThreadPoolExecutor 和 未来任务。

异步任务由运行在 后台线程,其结果发布在 UI 线程上。一个 异步任务由 3 种泛型类型定义,称为 Params, Progress 和 Result,以及 4 个步骤,分别称为 onPreExecute、doInBackground、 onProgressUpdate 和 onPostExecute。

http://developer.android.com/reference/android/os/AsyncTask.html

这是一种可视化异步任务的好方法:

(blog.fabgate.co)

基本上,您的任务很长。在 UI 线程中运行它会阻塞 UI,并可能导致您的应用程序崩溃。但是,如果您使用 Aysync 任务,您可以在单独的线程中执行它,同时使用 onProgressUpdate() 方法显示进度条或完成百分比。

这是一个从 AsyncTask 下载文件并提供信息的示例。向主 UI 线程了解进度:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

urls 是一个数组,其中包含用户请求下载的 URL。一个简单的 for 循环遍历每个请求的 URL,并使用 onProgressUpdate 方法发布进度,以便向用户显示他们的任务正在完成。

编辑:

对你来说,我认为你应该把这段代码:

try {
                Session session = Session.getDefaultInstance(props, null);
                Store store = session.getStore("imaps");
                try {
                    store.connect("imap.mail.yahoo.com", _Account[_i], _Pass[_i]);
                } catch (AuthenticationFailedException e) {
                }
                if(store.isConnected() == true){
                    _textArea.setText(_Account[_i]+"/"+_Pass[_i]+ "\n" + _textArea.getText() );
                }else{

                    _textArea_1.setText(_Account[_i]+"/"+_Pass[_i] + "\n" +_textArea_1.getText());

                }
            } catch (Exception e) {
            }

进入异步任务。像这样。您想在后台执行此操作,因此使用 doInBackground 方法:

 protected Void doInBackground(Void... params) 

  try {
                Session session = Session.getDefaultInstance(props, null);
                Store store = session.getStore("imaps");
                try {
                    store.connect("imap.mail.yahoo.com", _Account[_i], _Pass[_i]);
                } catch (AuthenticationFailedException e) {
                }
                if(store.isConnected() == true){
                    _textArea.setText(_Account[_i]+"/"+_Pass[_i]+ "\n" + _textArea.getText() );
                }else{

                    _textArea_1.setText(_Account[_i]+"/"+_Pass[_i] + "\n" +_textArea_1.getText());

                }
            } catch (Exception e) {
            }

并在 onProgressUpdate() 方法中设置进度条。它在主线程上运行,因此您可以直接从该方法本身设置进度条。

如果这有帮助,请告诉我,

鲁基尔

【讨论】:

  • 谢谢我所需要的,你能在java中修改我的新代码吗:(
  • 我不知道如何在我的项目中实现此代码
  • @hakimRasfi 好的,我已经用你的代码编辑了我的答案。有用的话请点个赞!告诉我
  • 抱歉,我现在看不到 --> 感谢您的反馈!一旦您总共获得 15 名声望,您的投票将改变公开显示的帖子分数
  • 没关系,我很高兴能帮上忙!如果您还有其他问题,请随时提问!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多