首页 > 解决方案 > 如何在没有属性类的情况下拥有相同的程序,这里是 int 私有计数器

问题描述

我想获得相同的效果和相同的代码,但不使用任何类属性或任何静态属性。

这里的类属性是 int 私有计数器,我想删除它并使用其他给我相同效果的东西

public class main extends Application{
    
    private int counter=0; 

    public static void main(String[] args) {

    launch(args);

    }
    
     public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("add and sub");
     
     Button b = new Button("+");
     Button b2 = new Button("-");
     
     GridPane root = new GridPane();
     Label l = new Label("0");
     root.add(b, 0, 0);
     root.add(l, 0, 1);
     root.add(b2, 0, 2);
     b.setOnAction(e ->
     {
     counter++;
     l.setText(""+counter);
     });
     b2.setOnAction(e ->
     {
     counter--;
     l.setText(""+counter);
     });

     Scene scene = new Scene(root, 300, 100);
     primaryStage.setScene(scene);
     
     primaryStage.show();   
}

标签: javaclassjavafxattributes

解决方案


您可能希望稍后将计数器用于其他用途,或者在 UI 输入之外增加它。

“int”和 lambdas 的问题是,lambdas 是“匿名类”的快捷表示。在methodscope中,“int增量”会造成麻烦,除非你在另一个对象上做静态(不推荐),或者有一个对象容器。您只能在 Lambda 中使用有效的最终对象。不允许对在 Lambda 表达式之外初始化的对象进行重新分配操作。

您可以使用属性对象。你想增加计数器,然后增加的计数器应该在视图中表示。意味着当计数器改变时标签应该改变。有时可能不是按钮更改计数器,而是您计算或从请求中接收到的东西。

或者你想更新时间或其他什么

public void start(Stage primaryStage) throws Exception {
     primaryStage.setTitle("add and sub");

     // this is a way that allows you to Have a Object
     // that is observable and can notify a change to something else
     // it has a value of the Type Integer
     IntegerProperty counter= new SimpleIntegerProperty(0);

     Button b = new Button("+");
     Button b2 = new Button("-");

     GridPane root = new GridPane();
     Label l = new Label("0");
     root.add(b, 0, 0);
     root.add(l, 0, 1);
     root.add(b2, 0, 2);

     // Here do you increment and decrement the counter
     b.setOnAction(e ->
      {
          counter.set(counter.get()+1);

      });
     b2.setOnAction(e ->
      {
          counter.set(counter.get()-1);
      });


     // Now you want to have the Label uptdated whenever the counter changes
     // you add a listener wich has the the Parameters: the object itself, the old value, 
     //and the new Value.
     // this method will be called whenever the Property changes. Not only if you push a 
     // button. It will always update the Label
     counter.addListener((obj,oldValue,newValue)->{

            outText.setText("" + newValue);

        });

     Scene scene = new Scene(root, 300, 100);
     primaryStage.setScene(scene);

     primaryStage.show();   
}


推荐阅读