Java:在线程化时更改标签值

时间:2015-10-13 14:44:20

标签: java multithreading label

我想创建一个小循环,在我按下GUI上的按钮后,每秒都会改变一个值;我试过使用一个线程,但我似乎无法使其正常工作。现在发生的是,按下按钮后程序暂停10秒钟。你能帮帮我吗?

这是我的代码看起来像

private void ButtonActionPerformed(java.awt.event.ActionEvent evt) { 

for (x = 0; x <= 10; x++)
    {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt(); here.
        }


        nummerlabel.setText(String.valueOf(x));
    }



}

4 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是 Public CU_Name As String Sub RegulatorFormat() Dim wks As Worksheet Dim wks2 As Worksheet Dim iCol As Long Dim lastRow As Long Dim Desc As Range Dim lastCol As Long Application.ScreenUpdating = False Worksheets.Select Cells.Select Selection.ClearFormats Call FormulaBeGone ActiveSheet.Cells.Unmerge CU_Name = [B1].Value lastRow = Range("C" & Rows.Count).End(xlUp).Row Set Desc = Range("A1", "A57") Desc.Select For Each wks In ActiveWindow.SelectedSheets With wks On Error Resume Next For iCol = 16 To 4 Step -1 Dim PerCol As Date PerCol = Cells(1, iCol) .Columns(iCol).Insert Range(Cells(1, iCol), Cells(lastRow, iCol)) = CU_Name .Columns(iCol).Insert Range(Cells(1, iCol), Cells(lastRow, iCol)) = Desc.Value .Columns(iCol).Insert Cells(1, iCol).Value = PerCol Range(Cells(1, iCol), Cells(lastRow, iCol)) = Cells(1, iCol) Range(Cells(1, iCol), Cells(lastRow, iCol)).NumberFormat = "mm/dd/yyyy" Next iCol End With Next wks Rows("1:2").EntireRow.Delete Columns("A:C").EntireColumn.Delete lastCol = ws.Cells.Find(What:="*", _ After:=ws.Cells(1, 1), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column For Each wks2 In ActiveWindow.SelectedSheets With wks2 On Error Resume Next For iCol = 52 To 6 Step -4 lastRow = Range("C" & Rows.Count).End(xlUp).Row Set CutRange = Range(Cells(1, iCol), Cells(54, iCol - 3)) CutRange.Select Selection.Cut Range("A" & lastRow + 1).Select ActiveSheet.Paste Next iCol End With Next wks2 Columns("E:ZZ").Select Selection.EntireColumn.Delete Application.ScreenUpdating = True Rows("1").Insert [A1] = "Period" [B1] = "Line#" [C1] = "CU_Name" [D1] = "Balance" Columns("E:BM").Select Selection.Delete Shift:=xlToLeft Call Save End Sub Sub FormulaBeGone() Worksheets.Select Cells.Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues ActiveSheet.Select Application.CutCopyMode = False End Sub Sub Save() Dim newFile As String newFile = CU_Name ChDir ("W:\ALM\Statistics\MO Automation\2015") 'Save folder ActiveWorkbook.SaveAs Filename:=newFile 'Later should seperate CU's into folder by province and year End Sub 类附带的Timer类。阅读the documentation,它可以帮助您解决问题。

答案 1 :(得分:1)

一个简单的规则是使用ExecutorService并将代码作为runnable运行。这不会阻止程序的全局流程。记得关闭执行程序。

private void ButtonActionPerformed(java.awt.event.ActionEvent evt) { 

    ExecutorService executorService =  Executors.newFixedThreadPool(1);     
    for (int x = 0; x <= 10; x++) {     
        final int y=x;
        executorService.execute(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            //nummerLabel should be accessed via final reference                        
            nummerlabel.setText(String.valueOf(y));
            }
        });

    }
    executorService.shutdown();

}

答案 2 :(得分:0)

在动作监听器(或任何事件处理程序)中调用Thread.sleep()将导致程序在sleep()调用期间无响应。

像Java Swing这样的GUI框架通常有一个事件调度线程(EDT)来处理所有键盘和鼠标输入。事件处理程序在 EDT中称为,并且由于只有一个EDT,因此必须一次调用它们。在当前事件的处理程序返回之前,您的程序无法响应下一个事件。

就像Jimmy Jutt在他的回答中所说的那样,以后或者在GUI程序中定期发生事情的正确方法是使用某种计时器(例如,{{1} })。计时器可用于安排未来的定时事件,您可以使用与为密钥和鼠标事件编写处理程序相同的方式编写处理函数。

答案 3 :(得分:0)

private void ButtonActionPerformed(java.awt.event.ActionEvent evt) {

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                for (int i = 0; i <= 10; i++) {
                    nummerlabel.setText(String.valueOf(i));

                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
}