2012-12-17 26 views
0

在過去的幾個月中,我嘗試過使用Java進行編程,並且大部分都沒有遇到任何問題,但現在我在使用空格時遇到了一些麻煩。在我的程序中,用戶按下一個按鈕,目標是在JLabel上顯示多條消息,這些消息通過Thread.sleep()方法展開。出於某種原因,只有最後一個最終被髮送。這是我的代碼。這不是全部,但我很確定問題在這裏。那裏的錯誤輸出是試圖看看代碼中發生了什麼,但顯然他們並沒有結束工作。在Java中使用多個空格

private class ClickListener implements ActionListener 
{  
    public void actionPerformed(ActionEvent e) 
    { 
     try { 
      if (e.getSource() == exitButton) 
       System.exit(0); 

      else if (e.getSource() == button1) 
       alValue = "This is the new message text."; 
      System.err.println(alValue); 
      createNewArrayList(); 
      Thread.sleep(3000); 
      alValue = "Back to invisible..."; 
      System.err.println(alValue); 
      createNewArrayList(); 
      Thread.sleep(2000); 
      alValue = ""; 
      System.err.println(alValue); 
      createNewArrayList(); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(EmptySpace.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
} 

private void createNewArrayList() { 
    ArrayList al = new ArrayList(); 
    al.add(alValue); 
    label1.setText("" + al); 
} 
+3

你是什麼意思「與空洞工作」? – Johnsyweb

+0

是否顯示「返回隱形...」值? – Amar

+0

@Amar,不,我沒有看到JLabel上顯示的值。只顯示最後一個。 – KrisC

回答

2

不要叫Thread.sleep()EDT,使用一個Swing Timer而不是範圍。相應地調整週期間隔以改變System.out調用之間的延遲。 總是使用大括號來闡明if陳述的範圍。

+0

謝謝,我會試試看。 – KrisC

+0

好吧,它與擺動定時器完美配合。謝謝您的幫助! – KrisC

0

我不知道這是否是一個錯字,但你有沒有定義alvalue爲的actionPerformed()函數中的一員。 並且還用Java縮進不是什麼措施,你需要把括號{}

if (e.getSource() == button1) 
    { 
       alValue = "This is the new message text."; 
       System.err.println(alValue); 
       createNewArrayList(); 
       Thread.sleep(3000); 
       alValue = "Back to invisible..."; 
       System.err.println(alValue); 
       createNewArrayList(); 
       Thread.sleep(2000); 
       alValue = ""; 
       System.err.println(alValue); 
       createNewArrayList(); 
} 
+0

alValue定義在代碼的其他地方,所以不,這絕對不是問題。我嘗試在括號中添加,但代碼似乎仍然運行相同。 – KrisC

相關問題