Java Eclipse - clicker计数器 - 不递增

时间:2011-06-23 14:32:24

标签: eclipse

非常简单,因为我是java Eclipse的新手。将Eclipse IDE用于Java开发人员 版本:Helios Service Release 2.创建了一个按钮和标签。使用此按钮可以在时间上将值递增1,但不会发生任何事情。不知道为什么不。请有人看看。我不认为我离我太远了。提前谢谢......

 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 ; // *
    }
 }
);

修改代码并在类声明之后放置int变量并在button1.addActionListener之后放置jut(新的ActionListener()方法标题并且没有成功

3 个答案:

答案 0 :(得分:1)

每次单击按钮时,您将counter设置为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));
 }
 }
 );

答案 1 :(得分:0)

查看代码的这个片段:

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

答案 2 :(得分:0)

也许我错了,但你的计数器变量总是1,因为它在增量操作之前就被初始化了。

按照以下方式移动初始化:

public class First {
    int counter = 0;

让counter = counter + 1停留在现在的位置