簡體   English   中英

如何使用延遲的while循環每次更新jLabel

[英]how to update a jLabel every time with a while loop with a delay

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  int count = jSlider1.getValue(); 
  int delay = jSlider2.getValue();
    int valueOfSlider = jSlider2.getValue();
     int valueOfSlider2 = jSlider1.getValue();

while (count > 0) 
{ 
    count--;
    String count2 = ""+count; 
  jLabel3.setText(count2);
try {Thread.sleep(delay); }
catch (InterruptedException ie) { }

 }

它最終將顯示jLabel上的最終數字,但它不會逐步更新數字。 任何幫助

Swing是單線程的 因此, 在EDT中永遠不應該進行長時間運行的任務 這包括睡覺。 而是使用javax.swing.Timer 這將延遲后台線程,然后發布要在EDT中執行的操作。

也可以看看:


import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public final class JLabelUpdateDemo {

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

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame("Update JLabel Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(JTimerLabel.getInstance());
        frame.setSize(new Dimension(275, 75)); // used for demonstration purposes
        //frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        Timer t = new Timer(1000, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                int val = Integer.valueOf(JTimerLabel.getInstance().getText());
                JTimerLabel.getInstance().setText(String.valueOf(++val));
            }
        });
        t.start();
    }

    private static final class JTimerLabel extends JLabel{
        private static JTimerLabel INSTANCE;

        private JTimerLabel(){
            super(String.valueOf(0));
            setFont(new Font("Courier New", Font.BOLD,  18));
        }

        public static final JTimerLabel getInstance(){
            if(INSTANCE == null){
                INSTANCE = new JTimerLabel();
            }

            return INSTANCE;
        }
    }
}

SSCCE模仿計數器,該計數器將從每秒0計數(即更新JLabel實例),直到應用程序終止。

你的問題是你在ActionPerformed回調中做了一些耗時的事情,它在事件線程中執行。 在回調中,你應該快速做一些事情並返回,即使這個“東西”正在產生一個線程。 當您占用事件線程時,GUI無法更新,它只會在您的回調返回后更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM