我想在actionlistener中按特定顺序执行任务。在我的代码中我希望在按钮上的主要任务执行时显示动作上的加载图标。但是当我按下d按钮时,一切都在同一时间完成..我希望JLabel img在执行任务之前显示我的图像数据库连接......我的代码是
take.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ev){
img.setIcon(image);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String formatted = format1.format(cal.getTime());
String dname = (String)doclist.getSelectedItem();
try{
db.connect();
rs=db.stmt.executeQuery("Select * from table4 where name='"+dname+"'");
rs.next();
final String id=rs.getString("dr_id");
String mst=rs.getString("mor_start");
String est=rs.getString("eve_start");
int mmax=rs.getInt("mor_max");
int emax=rs.getInt("eve_max");
int mava=rs.getInt("mor_ava");
int eava=rs.getInt("eve_ava");
}});
答案 0 :(得分:2)
使用SwingWorker
。有关详细信息,请阅读Concurrency上的Swing教程中的部分。
答案 1 :(得分:0)
@camickr说,您可以使用SwingWorker
。这里有一个完整的example。这个想法是你在另一个后台线程中运行一些进程,而不是与GUI在同一个线程中。 gui东西在Event Dispatch Thread中运行。
这里有一个例子:
class Worker extends SwingWorker<Void, String> {
private JLabel labelToUpdate;
private final String dname;
public Worker(JLabel label, String dname){
super();
this.labelToUpdate=label;
this.dname=dname;
}
@Override
protected void doInBackground() throws Exception {
//here you make heavy task this is running in another thread not in EDT
// you connect to the db and make the query you can call
// publish("connectin to the db") and this will call process
// Connection con = ...
}
@Override
protected void process(List<String> chunks) {
StringBuilder sb = new StringBuilder();
for(String chunk : chunks){
sb.append(chunk).append("\n");
}
labelToUpdate.setText(sb.toString());
}
//Executed on the Event Dispatch Thread after the doInBackground method is finished
@Override
protected void done(){
labelToUpdate.setIcon(null);
}
}
并在actionListener中
take.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ev){
String dname = (String)doclist.getSelectedItem();
SwingWorker worker = new Worker(label,dname);
label.setIcon(image);
worker.execute();
}
);