如何在执行按钮单击时保持应用程序工作 java
How to keep application work when executing button click java
当我单击复选按钮时,应用程序在处理作业时停止。
我想获得实时结果。
这是我的代码。
我用这个应用程序检查了一些雅虎帐户。
点击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
}
}
使用 AsysncTask。
AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler
and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the
most.) If you need to keep threads running for long periods of time,
it is highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor, ThreadPoolExecutor and
FutureTask.
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread. An
asynchronous task is defined by 3 generic types, called Params,
Progress and Result, and 4 steps, called onPreExecute, doInBackground,
onProgressUpdate and 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() 方法中设置进度条。它在主线程上运行,因此您可以直接从该方法本身设置进度条。
如果有帮助请告诉我,
鲁奇尔
当我单击复选按钮时,应用程序在处理作业时停止。
我想获得实时结果。
这是我的代码。
我用这个应用程序检查了一些雅虎帐户。
点击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
}
}
使用 AsysncTask。
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
http://developer.android.com/reference/android/os/AsyncTask.html
这是一种可视化异步任务的好方法:
基本上,您的任务很长。 运行 它在 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() 方法中设置进度条。它在主线程上运行,因此您可以直接从该方法本身设置进度条。
如果有帮助请告诉我,
鲁奇尔