2011-06-23 25 views
0

非常簡單,因爲對於Eclipse Eclipse來說是非常新穎的東西。使用Eclipse IDE for Java Developers 版本:Helios Service Release 2.創建了一個按鈕和標籤。使用此按鈕在時間上增加值1,但沒有任何事情發生。不知道爲什麼沒有。請有人看看。我認爲我再也不會離我太遠了。由於事先...Java Eclipse - clicker counter - 不會遞增

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 

    public class First 
    { 
     //int counter = 0; // tried it here -> unsuccesfull 
     // static int counter = 0; // tried it here -> unsuccesfull 

     public static void main (String [] args){ 
     JFrame frame = new JFrame("att"); 
     frame.setVisible(true); 
    frame.setSize(500,500); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel panel = new JPanel(); 
    frame.add(panel); 

     JButton button = new JButton("+"); 
     frame.add(panel); 
    panel.add(button); 

     JLabel label = new JLabel("1"); 
    frame.add(panel); 
    panel.add(label); 

     // int counter = 0; // tried it here -> unsuccesfull 

     // final int counter = 0; // tried it here -> unsuccesfull. Getting error 
     // "The final local variable counter cannot be assigned, since it is 
     // defined in an enclosing type" * 

     button1.addActionListener(new ActionListener() 
     { 
     public void actionPerformed(ActionEvent arg0) 
    { 
      label1.setVisible(true); 
     int counter = 0; 
     counter = counter + 1 ; // * 
    } 
} 
); 

改性的代碼,並放置類declartion後int變量和button1.addActionListener(新的ActionListener()方法報頭和沒有成功

回答

1

要設置爲0後突出部分

如果你想要跟蹤按鈕被點擊的次數,那麼你想聲明變量超出監聽器,否則,每次你點擊按鈕counter將永遠被聲明並設置爲0.因此,我噸不會像你期望的那樣增加。

你應該嘗試這樣的事:

static int counter = 0; 

    public static void main (String [] args){ 
    JFrame frame = new JFrame("att"); 
    frame.setVisible(true); 
    frame.setSize(500,500); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JPanel panel = new JPanel(); 
    frame.add(panel); 

    JButton button1 = new JButton("+"); 
    frame.add(panel); 
    panel.add(button1); 

    final JLabel label1 = new JLabel("0"); 
    frame.add(panel); 
    panel.add(label1); 

    button1.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent arg0) 
{ 
     label1.setVisible(true);   
     counter += 1 ; // * 
     label1.setText(String.valueOf(counter)); 
} 
} 
); 
+0

嘗試用自己的方式。不成功。 – DiscoDude

+0

現在,您必須設置計數器的標籤 – Bartzilla

+0

此外,您沒有將值分配給標籤。看到編輯後的版本,它應該工作。請記住,counter是一個靜態變量,它基本上意味着該值對於特定類的所有實例都是通用的。如果你想挖掘主題檢查[this](http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html) – Bartzilla

0

看這個片段你的代碼:

public void actionPerformed(ActionEvent arg0) 
    { 
      label1.setVisible(true); 
     int counter = 0; // you are setting variable to 0 
     counter = counter + 1 ; 
    } 
0

也許我錯了,但你的計數器變量將始終爲1,因爲它是在增量操作之前被初始化。

將其初始化這樣的:

public class First { 
    int counter = 0; 

,讓計數器計數= + 1個住宿的地方,現在

+0

我在VS中用C#和C++完成了這項工作。沒問題 – DiscoDude