gpt4 book ai didi

java - 如何在执行按钮单击java时保持应用程序工作

转载 作者:行者123 更新时间:2023-12-01 10:30:53 24 4
gpt4 key购买 nike

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

我想获得实时结果。

这是我的代码。

我使用此应用程序检查一些雅虎帐户。

当我点击检查时,我想一一得到结果,但是当我点击检查时,我必须等到所有帐户都被检查完,然后才能得到结果。

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

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

enter image description here (博客.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 - 如何在执行按钮单击java时保持应用程序工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com