2013-03-06 123 views
0

如何在while循环中更新jLabel?我的理解是使用javax.swing.timer,但我不太了解它,因为我需要执行一个动作,现在这是一个while循环,需要在每次通过while循环时更新一个计数器。如何在while循环中更新jLabel

有没有更简单的方法来做到这一点,如果是这样,我应该用什么来代替jLabel?

示例代码低于我需要更新的内容。

int rowCount = 0; 
    while(rowIterator.hasNext()) 
    { 


     jLabel5.setText(""+ rowCount); //<-- i need this to update 
     myRow = sheet.getRow(count); 
     cellIterator = myRow.cellIterator(); 
     Cell myCell2 = myRow.getCell(0); 
     nextCell= myCell2.getStringCellValue(); 


     if(nextCell.equals(firstCell)) 
     { 

      while(cellIterator.hasNext()) { 

          Cell cell = cellIterator.next(); 

          switch(cell.getCellType()) { 
           case Cell.CELL_TYPE_BOOLEAN: 
            System.out.print(cell.getBooleanCellValue() + "\t\t"); 
            break; 
           case Cell.CELL_TYPE_NUMERIC: 
            cell.setCellType(Cell.CELL_TYPE_STRING); 

            System.out.print(cell.getStringCellValue()+","); 

            //System.out.print(cell.getStringCellValue() + "\t\t"); 
            writer.write(cell.getStringCellValue()+","); 
            break; 
           case Cell.CELL_TYPE_STRING: 
            System.out.print(cell.getStringCellValue()+","); 
            //System.out.print(cell.getStringCellValue() + "\t\t"); 
            writer.write(cell.getStringCellValue()+","); 
            break; 
          } 
         } 
      System.out.println(); 
      writer.newLine(); 
      count++; 
      rowCount++; 



     } 
     else 
     {   

      writer.close(); 
      myRow = sheet.getRow(count); 
      myCell2= myRow.getCell(0); 
      nextCell=myCell2.getStringCellValue(); 
      firstCell=nextCell; 
      Matter = "Matter Number: "+firstCell; 
      num = firstCell; 
      System.out.println(Matter); 
      fWriter = new FileWriter(new File(directory, num+"_"+curdate+"_"+curtime+".csv")); 
      writer = new BufferedWriter(fWriter); 
      writer.write(Matter); 
      writer.newLine(); 
      writer.write(header); 
      writer.newLine(); 
     } 


    } 
} 
catch (Exception e) 
{ 
} 

回答

3

你的问题是Swing是单线程enironment。也就是说,只有一个线程负责分派所有事件并处理所有的重绘请求。

任何阻止此线程的操作都将阻止它更新UI(或响应新事件),从而使您的UI看起来像挂起。

您拥有的另一个问题是,应该只在该线程的上下文中执行UI的所有更新(您不应该尝试从另一个线程更新UI)。

在您的情况下,javx.swing.Timer不会帮助,因为定时器会定期“嘀嗒”一声,您需要一些可以用来回调EDT以执行所需更新的操作。

在这种情况下,我建议你使用SwingWorker

你可以看看

对于一些例子和想法

0

如果你想如果你想显示最后一个值,那么简单的节目内容,以显示所有的值,那么

String temp = ""; 
while(i < 100) { 
    temp += "" + i; 
    jLabel1.setText(temp); 
    i++; 
} 

while(i < 100) { 
    jLabel1.setText(i); 
    i++; 
} 
+1

这不是去工作,它会阻止教育署T,并阻止它处理任何重绘请求,直到循环(及其包含的方法)存在之后 – MadProgrammer 2013-03-06 09:01:18

+0

这是不可能的,基本上我试过要做的事情,那就需要有一种睡眠,只要我有关使得文本在循环内更新。例如,每当循环通过时,文本必须在jLable上更改,因此对于int,它必须从字面上显示标签中发生的计数。 – Silentdarkness 2013-03-06 09:05:00

+0

因此,您调用'setText',它会在EDT上提出请求以更新UI并在将来某个时间,但同时,您将继续循环,防止EDT处理重新绘制请求并发生。最糟糕的是,你建议在美国东部时区“睡觉”,甚至更糟糕,从美国东部时间以外更新用户界面。 – MadProgrammer 2013-03-06 09:06:33