错误:使用相同的方法在JavaFX中运行对象数组

时间:2014-05-23 23:48:40

标签: javafx

以下是代码:

主档案

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package testobjectarray;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * 
 */



public class TestObjectArray extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);

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

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * The main() method is ignored in correctly deployed JavaFX application. main() serves only as fallback in case the application can not be launched through deployment artifacts, e.g., in IDEs
     * with limited FX support. NetBeans ignores main().
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);

        myClass[] c = new myClass[5];
        c[2].myMethod();
    }

}

在外面宣布的类:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package testobjectarray;

/**
 *
 * 
 */
public class myClass {
    public void myMethod(){
        System.out.println("Inside myMethod");
    }
}

问题,我编译时出错,即初始化对象数组并调用方法。如果我只有一个对象,那么效果很好。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您的代码的问题是您正在初始化一个大小为5的数组,但您永远不会为其添加值。请尝试以下代码

myClass[] c = new myClass[5];
c[0] = new myClass();
c[1] = new myClass(); // and so on till c[4]
//now you can call the methods
c[1].myMethod();