2013-02-02 78 views
2

當點擊按鈕 時,有什麼辦法刷新jLabel中的計數器嗎?我試着用repaint(),revalidate()方法,但都不起作用。在jLabel刷新計數器

當像按鈕上點擊:

jButton_like.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent e) { 
       int count = 1; 
       eForumLikeCounter likeAmount = new eForumLikeCounter(
         userName, topicId, count); 
       if (likeAmount.checkLikeAmount() == true) { 
        JOptionPane 
          .showMessageDialog(null, 
            "Unable to perform like on the same thread by the same user"); 
       } else if (likeAmount.checkDislikeExists() == true) { 
        JOptionPane 
          .showMessageDialog(null, 
            "You can only either like or dislike this thread"); 
       } else { 
        likeAmount.likeCounter(); 
       } 
      } 
     }); 
    } 

建立了數據庫:

public void SetUpLikeDislikeAmount() { 
    int likes = 0; 
    int dislike = 0; 
    // Set Up Database Source 
    db.setUp("IT Innovation Project"); 
    String sql = "Select likeDislike_likes,likeDislike_dislike from forumLikeDislike WHERE likeDislike_topics = " 
      + topicId + ""; 
    ResultSet resultSet = null; 
    // Call readRequest to get the result 
    resultSet = db.readRequest(sql); 
    try { 
     while (resultSet.next()) { 
      likes += resultSet.getInt("likeDislike_likes"); 
      dislike += resultSet.getInt("likeDislike_dislike"); 
     } 
     resultSet.close(); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
    jLabel_like.setText(Integer.toString(likes)); 
    jLabel_dislike.setText(Integer.toString(dislike)); 
} 

在此先感謝。

+0

對於更早的幫助後SSCCE? – Amarnath

+0

我試圖做喜歡和不喜歡的系統。所以無論何時點擊按鈕,標籤中的值都會刷新。數據庫中的數據完美工作,只是我不知道如何刷新/更新jLabel。 – Rauryn

+0

點擊發生時使用'JLabel.setText'方法。 – Amarnath

回答

2

只需使用JLabelsetText()方法。大概是這樣的:

counter.setText(""); 

counter.setText("0"); 
+0

我試過label.setText(SetUpLikeDislikeAmount());但是關於什麼不能從void轉換爲字符串有一個錯誤。 – Rauryn

+0

setText()方法需要一個String作爲參數。您應該閱讀JLabel的javadoc。 –

+0

好的,好的,非常感謝。我已經修好了 – Rauryn