如何在java中使用进度条?

时间:2014-09-24 16:38:23

标签: java loops process progress

我想在java GUI中显示进度条中的进度,但在进程完成之前,进度不会显示任何内容。

这是我的尝试:

public void selectTweet(){
   Connection conn = null;
   Statement stmt = null;
   try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = Drive

        rManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();

        //menghitung jumlah query pada table tweet
        String sql = "SELECT COUNT(*) FROM tweet";
        ResultSet rs=stmt.executeQuery(sql);
        int row = 0;
        while(rs.next()){
            row = rs.getInt("COUNT(*)");
        }

        int initial_number = Integer.parseInt(jTextField4.getText());

        for(int i=initial_number;i<row;i++){
            System.out.println("tweet ke-"+i);
            String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
            ResultSet rs2 = stmt.executeQuery(sql1);

            while(rs2.next()){
                tweet = rs2.getString("tweet");
                date  = rs2.getString("date");
                location  = rs2.getString("location");
            }
            System.out.println("Tweet: " + tweet);
            removeStopWords(tweet, i, date, location);


            final int currentValue = i;
            try{
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        jProgressBar1.setValue(currentValue);
                    }
                });
                java.lang.Thread.sleep(100);
            }catch (InterruptedException e) {
                //JOptionPane.showMessageDialog(frame, e.getMessage());
            }
        }
    }catch(SQLException se){
        //Handle errors for JDBC
        se.printStackTrace();
    }catch(Exception e){
        //Handle errors for Class.forName
        e.printStackTrace();
    }finally{
        //finally block used to close resources
        try{
            if(stmt!=null)
            conn.close();
        }catch(SQLException se){}// do nothing
        try{
            if(conn!=null)
            conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }//end finally try
    }//end try
}

我想要做的是从数据库中删除字符串记录中的停用词,有5000条记录,然后我想使用进度条来显示该过程,但它不起作用。我错过了什么?请帮帮我。

2 个答案:

答案 0 :(得分:0)

您需要在单独的Thread中处理您的任务。如果您不这样做,则会阻止调用repaint方法的主Swing线程。另外,我在代码中看不到任何ProgressBar,您必须在执行任务的步骤时更新其值。

SwingUtilities.invokeLater(
    new Runnable(
       public void run() {
           for(int i=initial_number;i<row;i++){
              System.out.println("tweet ke-"+i);
              String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
              ResultSet rs2 = stmt.executeQuery(sql1);

              while(rs2.next()){
                  tweet = rs2.getString("tweet");
                  date  = rs2.getString("date");
                  location  = rs2.getString("location");
              }
              System.out.println("Tweet: " + tweet);
              removeStopWords(tweet, i, date, location);

              jTextArea1.append(toTextArea);
              // the JProgressBar must have been instantiated 
              // as new JProgressBar(initial_number,row - 1)
              jProgressBar1.setValue(i); 
          }
    }));

答案 1 :(得分:0)

将SwingWorker用于长时间运行的任务可以使事情变得更容易。

public void selectTweet()
{
    final int initial_number = Integer.parseInt(jTextField4.getText()); // This should be done outside of the worker because you are accessing a UI element's data.
    SwingWorker<Void, int[]> worker = new SwingWorker<Void, int[]>()
    {
        @Override
        protected Void doInBackground() throws Exception
        {
            Connection conn = null;
            Statement stmt = null;
            try
            {
                Class.forName( "com.mysql.jdbc.Driver" );
                conn = DriverManager.getConnection( DB_URL, USER, PASS );
                stmt = conn.createStatement();

                String sql = "SELECT COUNT(*) FROM tweet";
                ResultSet rs = stmt.executeQuery( sql );
                int row = 0;
                while( rs.next() )
                {
                    row = rs.getInt( "COUNT(*)" );
                }

                for( int i = initial_number; i < row; i++ )
                {
                    System.out.println( "tweet ke-" + i );
                    String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='" + i + "'";
                    ResultSet rs2 = stmt.executeQuery( sql1 );

                    String tweet, date, location;
                    while( rs2.next() )
                    {
                        tweet = rs2.getString( "tweet" );
                        date = rs2.getString( "date" );
                        location = rs2.getString( "location" );
                    }
                    System.out.println( "Tweet: " + tweet );
                    removeStopWords( tweet, i, date, location );

                    publish( new int[]{i,row} );
                }
            }
            catch( SQLException se )
            {
                //Handle errors for JDBC
                se.printStackTrace();
            }
            catch( Exception e )
            {
                //Handle errors for Class.forName
                e.printStackTrace();
            }
            finally
            {
                //finally block used to close resources
                try
                {
                    if( stmt != null )
                        conn.close();
                }
                catch( SQLException se )
                {
                }// do nothing
                try
                {
                    if( conn != null )
                        conn.close();
                }
                catch( SQLException se )
                {
                    se.printStackTrace();
                }//end finally try
            }//end try
        }

        @Override
        protected void process( List<int[]> chunks ) // Run in the EDT, so no invokeLater needed
        {
            if( chunks == null || chunks.isEmpty() )
                return;
            int[] last = chunks.get( chunks.size() - 1 );
            jProgressBar1.setMinimum( 0 );
            jProgressBar1.setMaximum( last[1] - initial_number );
            jProgressBar1.setValue( last[0] - initial_number );
        }

        @Override
        protected void done() // Run in the EDT, so no invokeLater needed
        {
            jProgressBar1.setValue( jProgressBar1.getMaximum() );
        }
    };
    worker.execute();
}