javafx窗格未创建

时间:2016-04-02 04:01:18

标签: java class javafx pane

我的JavaFx代码无法正常工作。我正在尝试创建填充了1或0的10X10文本矩阵,因此它看起来类似于填充了1&0和2的2d数组。当我把当前在MatrixPane类中的代码放在main中时,它工作正常,但是使用此代码它只是设置场景,但看起来没有添加或创建窗格。

如果有人可以帮助我,我会非常感激。

我意识到我已经导入了一些未使用的东西,我将它们用于程序的其他部分。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.FlowPane;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javafx.scene.shape.Arc;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.geometry.Pos;
import javafx.collections.ObservableList;

public class Button1 extends Application
{
    public void start(Stage primaryStage)
    {
        GridPane pane = new GridPane();
        MatrixPane Matrix = new MatrixPane();
        pane.getChildren().add(Matrix);

        Scene scene = new Scene(pane, 700, 500);
        primaryStage.setTitle("1 window "); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage
    }

    public static void main(String[] args)
    {
        Application.launch(args);
    }

}


class MatrixPane extends Pane
{
    double HEIGHT = 500;
    double WIDTH = 200;
    private GridPane pane1 = new GridPane();

    public MatrixPane()
    {
    }

    public void fillmatrix()
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                TextField text = new TextField(Integer.toString((int)(Math.random() * 2)));
                text.setMinWidth(WIDTH / 8.0);
                text.setMaxWidth(WIDTH / 10.0);
                text.setMinHeight(HEIGHT / 8.0);
                text.setMaxHeight(HEIGHT / 10.0);
                this.pane1.add(text, j, i);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

fillMatrix();

调用Button1.start()方法

在MatrixPane construcor中将GridPane添加到MatrixPane

private GridPane pane1 = new GridPane();

public MatrixPane() {
    getChildren().add(pane1);
}

这样可行。

答案 1 :(得分:0)

我检查了你的代码,你过度使用了GridPane。首先,您有一个名为MatrixPane的类,它继承Pane,但此类还有一个属性GridPane。最后,您再次使用GridPane添加MatrixPane

所以,我做的是使用合成,但首先我改变了start方法

public void start(Stage primaryStage) {

  GridPane pane = new GridPane();
  MatrixPane Matrix = new MatrixPane();
  //pane.getChildren().add(Matrix);
  Matrix.fillmatrix();
  Scene scene = new Scene(Matrix.getPane1(), 700, 500);
  ...

所以这里场景将接收pane1的数据,此属性具有在调用fillmatrix时存储的值。

然后我在MatrixPane中为属性pane1

添加了getter方法
class MatrixPane {

  double HEIGHT = 500;
  double WIDTH = 200;
  private GridPane pane1 = new GridPane();

  public GridPane getPane1() {
    return pane1;
  }
  ...