如何在JPanel上使用JLabel实现计时器?

时间:2014-12-01 04:36:41

标签: java multithreading user-interface timer

我想获取对象inst的set变量,然后将其设置为JLabel并将其设置为面板上已有的当前JLabel。但是我想要对象的变量(inst.Time(表示秒))' inst'减1并删除当前的JLabel并向面板添加更新的,减少的inst.Time。

我想减少1秒作为倒数计时器,直到它达到0并退出WaitAndEnterIntoWorkArea方法。有人可以用给定的代码说明如何这样做吗?请帮忙。谢谢

int.Time是一个整数

 private int WaitAndEnterIntoWorkArea(Instruction inst) // 'inst' is an object of Instruction arrayList
    {
        int index = 0;
        int nFirstYDirectionToMove = 1;

        JLabel busy = new JLabel(String.valueOf(inst.Time) + "s"); //inst.Time is a time that was set for that particular 'inst' and set the busy JLabel to show time + s, e.g. 5s or 3s (s represents seconds)
        busy.setFont(font3);
        busy.setForeground(Color.RED);

         if(inst.WorkArea.startsWith("anvil")) //If inst.WorkArea is set to "anvil" Go into the block of code
        {
            nFirstYDirectionToMove = 1; //Move over one (Not important)

                                                                      //I would like to decrement inst.Time 1 at a time to 0 and add to JPanel every second 
            while(true)
            {
                synchronized("row1" + String.valueOf(index)){
                    if(row1[index].getText().equalsIgnoreCase("Open")) //If JLabel row1[index].getText() is already set as text "Open" execute the if statement;
                    {
                                                                                                                              //I would like to remove the current JLabel (row1[index]) and add the 1 second decremented JLabel to the panel
                        panel.remove(row1[index]); //Remove the JLabel of row1[indexOfArea]  (row1 is an array of JLabels) from the panel
                        row1[index] = busy; //Set JLabel text of row1[index] to the busy JLabel //Set the 1 second decremented JLabel to the current JLabel
                        panel.add(row1[index]); //Add the JLabel with the new text label with something like e.g. 5s or 4s, etc. to the panel
                        revalidate();
                        repaint();
                        break;
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

如果我没弄错的话,只需拨打busy.setText(String.valueOf(inst.Time) + "s");就可以了。但与往常一样,我强烈建议使用JavaFX而不是Swing。

至于时间尝试

Timer timer = new Timer();
timer.scheduleAtFixedRate(()-> busy.setText(...), 0, 1000);