Java 仅执行SwingWorker的一个实例

Java 仅执行SwingWorker的一个实例,java,swing,concurrency,swingworker,Java,Swing,Concurrency,Swingworker,假设我有一个javagui,它在一个面板中显示了来自一个选定区域的40个批处理对象,可以从a到Z 这40个批处理对象是从数据库中查询出来的,该数据库按区域缓存它们,这样每次对区域的请求都不会涉及数据库 public class BatchView { private int drawIt(Graphics g, String zone) { for(int i = 0; i<40; i++) { Batch tmpBatch = Bat

假设我有一个javagui,它在一个面板中显示了来自一个选定区域的40个批处理对象,可以从a到Z

这40个批处理对象是从数据库中查询出来的,该数据库按区域缓存它们,这样每次对区域的请求都不会涉及数据库

public class BatchView
{

  private int drawIt(Graphics g, String zone)
  {
     for(int i = 0; i<40; i++)
       {
          Batch tmpBatch = BatchDAO.getBatch(zone, i);
          //draw the tmpBatch object
       }
  }
}

public class BatchDAO 
{
  public static MyCache cache = new MyCache(5000);

  public getAllBatches(String zone)
  {
    ArrayList<Batch> batchArrayList = cache.get("batch-" + zone);
    if(batchArrayList == null)
    {
        BuildBatchSwingWorker buildBatchSwingWorker = new BuildBatchSwingWorker(zone);
        buildBatchSwingWorker.execute();
    }
    return batchList;
  }

  public Batch getBatch(String zone, int id)
  {
     //here I don't query database but exploit the cache
     ArrayList<Batch> batchArrayList = getAllBatches(String zone);
     for(int i = 0; i< batchArrayList.size(); i++)
     {
       if(batchArrayList.get(i).getId() == i)
            return batchArrayList.get(i);
     }
     //if batch is not found it means it hasn't loaded yet so I return null
     return null;
  }
}
公共类批处理视图
{
专用int drawIt(图形g,字符串区域)
{

对于(int i=0;i给定您的代码,我认为真正关心的不是执行多少次,而是数据库只调用一次,然后使用
BatchDAO
的缓存

您需要正确地划分职责,缓存维护是
BatchDAO
类的工作,因此swing worker与此无关:

public class BatchDAO {
    ...
    public getAllBatches(String zone) {
        ArrayList<Batch> batchArrayList = cache.get("batch-" + zone);
        if(batchArrayList == null) {
            // here goes database call not swing worker!
        }
        return batchList;
    }
    ...
}
公共类BatchDAO{
...
公共getAllBatches(字符串区域){
ArrayList batchArrayList=cache.get(“批-”+区域);
if(batchArrayList==null){
//数据库调用不是swing worker!
}
返回批处理列表;
}
...
}
然后在GUI类(它所属的位置)中执行swing worker:

公共类批处理视图{
专用int drawIt(图形g,字符串区域){
SwingWorker worker=新SwingWorker(){
@凌驾
受保护的Void doInBackground()引发异常{

对于(inti=0;i这里是您可以调用的Swing实用程序的好例子:)

/*
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
包com.verve.swinguti;
导入javax.swing.SwingUtilities;
/**
*
*@作者基山
*/
公共类实用程序扩展了javax.swing.JFrame{
/**
*创建新的表单实用程序
*/
公用事业(){
初始化组件();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
// 
私有组件(){
jPanel1=newjavax.swing.JPanel();
jButton2=newjavax.swing.JButton();
jButton1=newjavax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setText(“jButton2”);
jButton2.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout=新的javax.swing.GroupLayout(jPanel1);
setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpanellayout.createSequentialGroup()
.addGap(71,71,71)
.addComponent(jButton2)
.addContainerGap(155,简称最大值))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jpanellayout.createSequentialGroup()
.addGap(118118118)
.addComponent(jButton2)
.addContainerGap(128,简称最大值))
);
setText(“jButton1”);
jButton1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT\u SIZE,javax.swing.GroupLayout.DEFAULT\u SIZE,Short.MAX\u值)
.addContainerGap())
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0,0,短.MAX_值))
.addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT\u SIZE,javax.swing.GroupLayout.DEFAULT\u SIZE,Short.MAX\u VALUE))
.addContainerGap())
);
包装();
}// 
私有void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
试一试{
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
对于(int i=0;i<10;i++){
System.out.println(“这是一个很好的示例**”);
《睡眠》(2000年);
}
}捕获(例外e){
e、 printStackTrace();
}
}
});
}捕获(例外e){
e、 printStackTrace();
public class BatchView {

    private int drawIt(Graphics g, String zone) {
        SwingWorker<Void, Batch> worker = new SwingWorker<Void, Batch>() {
            @Override
            protected Void doInBackground() throws Exception {
                for(int i = 0; i<40; i++) {
                    Batch tmpBatch = BatchDAO.getBatch(zone, i);
                    publish(tmpBatch);
                 }
                 return null;
             }

             @Override
             protected void process(List<Batch> batches) {
                 for(Batch batch : batches) {
                     //draw the batch object
                 }
             }
         };

         worker.execute();
    }

}
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.

    package com.verve.swinguti;

    import javax.swing.SwingUtilities;

    /**
     *
     * @author kishan
     */
    public class Utilities extends javax.swing.JFrame {

        /**
         * Creates new form Utilities
         */
        public Utilities() {
            initComponents();
        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {

            jPanel1 = new javax.swing.JPanel();
            jButton2 = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jButton2.setText("jButton2");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(71, 71, 71)
                    .addComponent(jButton2)
                    .addContainerGap(155, Short.MAX_VALUE))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(118, 118, 118)
                    .addComponent(jButton2)
                    .addContainerGap(128, Short.MAX_VALUE))
            );

            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            );

            pack();
        }// </editor-fold>

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            try {
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            for (int i = 0; i < 10; i++) {
                                System.out.println("This is Good Example**");
                                Thread.sleep(2000);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            try {
                System.out.println("This is Second Button");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /*
             * Set the Nimbus look and feel
             */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /*
             * If Nimbus (introduced in Java SE 6) is not available, stay with the
             * default look and feel. For details see
             * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Utilities.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Utilities.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Utilities.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Utilities.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /*
             * Create and display the form
             */
            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                    new Utilities().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
    }