-2

我想在 actionlistener 中按特定顺序执行任务。在我的代码中,我希望在执行按钮上的主要任务时显示加载图标。但是当我按下 d 按钮时,一切都同时完成了。数据库连接..这是我的代码

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");
          }});
4

2 回答 2

2

使用SwingWorker. 阅读 Swing 教程中关于并发的部分以获取更多信息。

于 2013-11-12T16:52:33.213 回答
0

你可以使用SwingWorker@camickr 说的。这里有一个完整的例子。这个想法是你在另一个后台线程中运行一些进程,而不是在与 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();  
    }
);
于 2013-11-12T17:07:08.167 回答