为ProgressBar Java添加容器侦听器

时间:2014-09-13 11:47:55

标签: java swing jprogressbar

请帮忙。这段代码不起作用。创建进度条,其中显示0%全部。我不太了解java.i正在寻求帮助。

原始代码:

 jProgressBar1.setName("");
        jProgressBar1.setValue(0);
        jProgressBar1.setStringPainted(true);
        jProgressBar1.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                jProgressBar1ComponentAdded(evt);
            }
        });
private void jProgressBar1ComponentAdded(java.awt.event.ContainerEvent evt) {                                             

    Task tk = new Task();
    tk.run();

        }    

 class Task extends Thread {    
    public Task(){}

    public void run(){
       for(int i =0; i<= 100; i++){
          final int progress = i;
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                 jProgressBar1.setValue(progress);

             }
          });
       }}}

最新代码:

import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

import javax.swing.*;




public class ini extends JFrame {


    public ini() {
        initComponents();

    }

    private void initComponents() {

            setResizable(false);
            jLabel1 = new JLabel();
            jProgressBar1 = new JProgressBar(0,100);
            jProgressBar1.addContainerListener(new ContainerAdapter() {
                @Override
                public void componentAdded(ContainerEvent e) {
                   if (jProgressBar1 == e.getChild()) {
                      System.out.println("progressBar!");
                      new Thread(new Task()).start();
                   }
                }
             });

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Criminal Records");

            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            jLabel1.setText("Criminal Records");

            jProgressBar1.setName("");
            jProgressBar1.setValue(0);
            jProgressBar1.setStringPainted(true);

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(204, 204, 204)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(215, 215, 215)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(242, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(312, 312, 312)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(348, Short.MAX_VALUE))
            );

            pack();

     }


    public static void main(String args[]) {


        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(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ini().setVisible(true);
            }
        });
    }

    private class Task implements Runnable {
        private static final long SLEEP_TIME = 100;

        @Override
        public void run() {
           for (int i = 0; i <= 100; i++) {
              final int progress = i;
              SwingUtilities.invokeLater(new Runnable() {
                 public void run() {
                    jProgressBar1.setValue(progress);

                 }
              });
              try {
                 Thread.sleep(SLEEP_TIME);
              } catch (InterruptedException e) {
                 e.printStackTrace();
              }
           }
        }
     }


    private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
}

1 个答案:

答案 0 :(得分:1)

我发现使用线程有一个主要问题和一个小问题:

  • 小问题:你应该实现一个Runnable,而不是扩展Thread,因为这会按照单一责任规则将Thread运行的代码与Thread分开,并且为线程运行的代码提供更大的灵活性,因为现在它如果需要,可以扩展其他类。
  • 当您开始一个主题时,请在其上调用.start(),而不是.run(),因为后者将保证不会创建后台主题。

关于您使用ContainerListener的其他问题,我等待您澄清问题,并创建并发布minimal code example program以供我们审核,测试和修复。


修改
根据你的评论,

  

我想在一个显示0-100%的框架中显示进度条。我创建了框架并添加了进度条。但它只显示0%,而不是移动。

同样,您有一些需要修复的线程问题。你还想在那里放一个Thread.sleep来减慢你的for循环。否则,即使使用正确的线程,您也不会看到进展。

  

我想在将progressbar添加到框架时调用该函数。

您正在向不会起作用的JProgressBar添加ContainerListener,因为您没有在进度条中添加任何内容。您需要将侦听器添加到保持进度条的容器中。但即便如此,这可能不是启动这一过程的好方法。但让我看看我能做些什么......请等一下。


如,

import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

import javax.swing.*;

public class JProgressExample extends JPanel {
   private JProgressBar jProgressBar1 = new JProgressBar(0, 100);

   public JProgressExample() {
      addContainerListener(new ContainerAdapter() {
         @Override
         public void componentAdded(ContainerEvent e) {
            if (jProgressBar1 == e.getChild()) {
               System.out.println("progressBar!");
               new Thread(new Task()).start();
            }
         }
      });
      jProgressBar1.setName("");
      jProgressBar1.setValue(0);
      jProgressBar1.setStringPainted(true);

      add(jProgressBar1);
   }

   private class Task implements Runnable {
      private static final long SLEEP_TIME = 100;

      @Override
      public void run() {
         for (int i = 0; i <= 100; i++) {
            final int progress = i;
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  jProgressBar1.setValue(progress);

               }
            });
            try {
               Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }
      }
   }

   private static void createAndShowGui() {
      JProgressExample mainPanel = new JProgressExample();

      JFrame frame = new JFrame("JProgressExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}