JavaFX:如何创建setUpGUI方法?

时间:2014-08-14 09:30:20

标签: user-interface methods javafx

我想设置一个设置GUI的方法。我试着用这种方式:

public class Test extends Application {
    GridPane root;

    @Override
    public void start(Stage primaryStage) {          
        root = setGUI();  
        Scene scene = new Scene(root, 300, 300);
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    private GridPane setGUI(){        
        GridPane root2 = new GridPane();        
        ColumnConstraints cc = new ColumnConstraints();
        RowConstraints rc = new RowConstraints();
        cc.setPercentWidth(10);
        rc.setPercentHeight(10);
        root2.getColumnConstraints().add(cc);
        root2.getRowConstraints().add(rc);
        for(int c = 0; c < 10; c++){            
            int w = (int) root2.getWidth()/10;
            int h = (int) root2.getHeight()/10;
            for(int r = 0; r < 10; r++){
                MyRectangle rec;
                if((r+c)%2 == 0){
                    rec = new MyRectangle(w, h, Color.GREY);
                }else{
                    rec = new MyRectangle(w, h, Color.DARKGRAY);
                }          
                System.out.println("w h "+w+" "+h);
            }  
        }
        return root2;
    }
    public static void main(String[] args) {
        launch(args);
    }
}

在许多其他人中,但从未得到过我想要的“棋盘效应”。我还尝试将root2设置为final,我尝试了许多其他更改,但没有管理它! 编辑: MyRectangle课程:

package test;

import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class MyRectangle extends Rectangle{
    public int clickedTimes = 0;
    public MyRectangle(int w, int h, Color c) {
        super (w, h, c);
    }   
}

1 个答案:

答案 0 :(得分:0)

即使将矩形添加到网格中,它也无法工作,因为以下几行:

int w = (int) root2.getWidth()/10;
int h = (int) root2.getHeight()/10;

您没有设置Width/Height的{​​{1}},因此它总是

您需要设置GridPane的大小,然后使用它来设置矩形的大小。一个工作的例子:

Gridpane