JavaFX中的对象数组

时间:2016-10-28 21:13:57

标签: java arrays javafx

我应该创建一个类型为int numberOfButtons = 20; for (int i = 0; i < numberOfButtons; ++i) { Button[] btn = new Button[numberOfButtons]; btn[i] = new Button(); btn[i].setText("Safe!"); btn[i].setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); FlowPane root = new FlowPane(); root.getChildren().addAll(btn[i]); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Button Blast!"); primaryStage.setScene(scene); primaryStage.show(); } 的对象数组,但输出只是一个按钮,不应该是多个按钮。我该怎么办?

{{1}}

2 个答案:

答案 0 :(得分:1)

当你遇到这样的问题时,最好的办法是拿一张纸和一支笔写下来  代码的每一行都有。

您的完整代码在循环中。你应该缩小范围,以便只包含这个:

#include <string>
#include <iostream>

//  abstract base class
class AB { 
public:
    virtual void setName(std::string s) = 0;

    // Doesn't compile if I don't have this:
    // Different error if pure or non-pure
    virtual void setValue(int value) = 0;
};

class D1 : public AB {
public:

  // Doesn't compile if I don't have this line, but it's
  // not applicable to D1.
  //
  //void setValue(int value) { }

    void setName(std::string s) {
      std::cout << "D1::setName to " << s << std::endl;
      name_ = s;
    }
private:
  std::string name_;
};

class D2 : public D1 { 

public:
  void setValue(int value) {
      std::cout << "D2::setValue to " << value << std::endl;
      val_ = value;
    }

private:
  int val_;
};

int main() {

    AB* pD1= new D1;
    AB* pD2= new D2;

    pD1->setName("a D1");

    pD2->setName("a D2");
    pD2->setValue(5);

  return 0;
}

答案 1 :(得分:0)

我使用JavaFx和Java8(Stream)来解决您的问题:

    FlowPane fPane = IntStream.range(1, 20)
            .mapToObj(value -> {

                Button button = new Button("Safe!");

                button.setOnAction(event -> {
                    System.out.println("Hello World!");
                });

                return button;

            }).reduce(new FlowPane(), (p, b) -> {

                p.getChildren().add(b);

                return p;
            }, (flowPane, flowPane2) -> flowPane2);

    Scene scene = new Scene(fPane, 300, 250);

    primaryStage.setTitle("Button Blast!");
    primaryStage.setScene(scene);
    primaryStage.show();