简体   繁体   English

JProgressBar 立即移动而不是逐渐移动 (java)

[英]JProgressBar moves instantly and not gradually (java)

I want to make a ProgressBar move gradually using a Jbutton.我想使用 Jbutton 使 ProgressBar 逐渐移动。 To achieve this I am using a for loop and the method Thread.sleep.为此,我使用了一个 for 循环和 Thread.sleep 方法。 The problem is that insted of moving a tiny bit every second (the progress bar) after pressing the button, the program waits until the loop finishes and then does instantly move the progress up.问题是按下按钮后每秒移动一点点(进度条),程序一直等到循环完成,然后立即向上移动进度。 When I take the loop outside of the button listener it works as I want but I really need it to work when pressing the button.当我将循环置于按钮侦听器之外时,它会按我想要的方式工作,但我确实需要它在按下按钮时工作。 Here is the code:这是代码:

progressBar.setOrientation(SwingConstants.VERTICAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setValue(50);
panel1.setLayout(null);
panel1.add(progressBar);
progressBar.setBounds(40,6,100,100);

button1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int counter = 5;
        for (int i = 0; i < 5; i++) {
            progressBar.setValue(progressBar.getValue() + counter);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
});

If anyone can help me I will be very grateful!如果有人可以帮助我,我将不胜感激!

Your code runs on the Event Dispatcher Thread (EDT).您的代码在事件调度程序线程 (EDT) 上运行。 That thread is responsible for handling events, but also for repainting.该线程负责处理事件,但也负责重新绘制。 Because it's just one thread, the repainting only occurs after your method ends.因为它只是一个线程,所以重绘只会在您的方法结束发生。

There are some ways to solve this.有一些方法可以解决这个问题。 In your case, a javax.swing.Timer would probably be easiest.在您的情况下, javax.swing.Timer可能是最简单的。 Instead of running the loop in a single method, the button click starts a timer that runs every second.单击按钮不是在单一方法中运行循环,而是启动一个每秒运行的计时器。 When it's done the timer can cancel itself.完成后,计时器可以自行取消。 A slightly more difficult alternative is to use a SwingWorker .一个稍微困难的替代方法是使用SwingWorker You could publish data in the doInBackGround method, and override process to perform the updates to the progress bar.您可以在doInBackGround方法中publish数据,并覆盖process以执行对进度条的更新。

For more information, please read Concurrency in Swing .更多信息请阅读Swing 中的并发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM