【问题标题】:How do I implement timer using JLabel on JPanel?如何在 JPanel 上使用 JLabel 实现计时器?
【发布时间】:2014-12-01 04:36:40
【问题描述】:

我想获取对象 inst 的设置变量,然后将其设置为 JLabel 并将其设置为面板上已经存在的当前 JLabel。但我希望对象“inst”的变量(inst.Time(表示秒))减一并删除当前的 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;
                    }
                }
            }
        }

【问题讨论】:

  • @MadProgrammer 你能帮忙吗?

标签: java multithreading user-interface timer


【解决方案1】:

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

至于时机尝试

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

【讨论】:

  • 但是我如何确保它每次将 JLabel 递减 1 秒?我相信我需要做 sleep(1000) 但我应该在哪里或如何使用它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
相关资源
最近更新 更多