2015-12-23 42 views
0

我试图在JavaFX中制作Suduko板。我听说TilePane对此特别好,因为TilePane背后的全部理念是每个“瓷砖”具有统一的尺寸。太棒了,这正是Suduko棋盘,棋盘,跳棋,井字游戏,战舰等等。听起来像TilePane是任何类型的棋盘游戏应用程序的必备窗格。JavaFX TilePane setPrefColumn/Row方法不工作?

或者是?

import javafx.application.Application; 
import javafx.application.Platform; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.control.TextFormatter; 
import javafx.scene.control.TextFormatter.Change; 
import javafx.scene.image.Image; 
import javafx.scene.layout.TilePane; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

public class SudukoSolver extends Application 
{ 
    Stage window; 
    Scene scene; 
    private final int TEXTFIELD_WIDTH = 32; 
    private final int TEXTFIELD_HEIGHT = 32; 

    @Override public void start(Stage window) throws Exception 
    {  
     this.window = window; 
     window.setTitle("Suduko Solver"); 
     window.setOnCloseRequest(e -> closeProgram()); 

     // Does setting this to false defeat the purpose of TilePane? 
     window.setResizable(false); 

     VBox root = new VBox(); 
     //root.setAlignment(Pos.CENTER); 

     TilePane tiles = new TilePane();  
     tiles.setAlignment(Pos.CENTER); 

     // Does not appear to do anything. 
     tiles.setPrefColumns(9); 
     tiles.setPrefRows(9); 

     // Add all the tiles to the Pane. 
     root.getChildren().add(tiles); 

     for (int i = 0; i < 81; i++) 
     { 
      TextField textBox = new TextField(); 
      textBox.setMinHeight(TEXTFIELD_HEIGHT); 
      textBox.setMaxHeight(TEXTFIELD_HEIGHT); 
      textBox.setMinWidth(TEXTFIELD_WIDTH); 
      textBox.setMaxWidth(TEXTFIELD_WIDTH); 

      textBox.setTextFormatter(new TextFormatter<String>((Change change) -> 
      { 
       String newText = change.getControlNewText(); 
       if (newText.length() > 1) 
       { 
        return null ; 
       } 
       else if (newText.matches("[^1-9]")) 
       { 
        return null; 
       } 
       else 
       { 
        return change ; 
       } 
      })); 

      tiles.getChildren().add(textBox); 
     } 


     scene = new Scene(root, 600, 750); 
     window.setScene(scene); 
     window.show(); 
    } 

    /** 
    * This method is called when the user wishes to close the program. 
    */ 
    private void closeProgram() 
    { 
     Platform.exit(); 
    } 

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

请注意,这不是9x9网格。

enter image description here

任何帮助将不胜感激。谢谢!

回答

3

在您的代码中,您的TilePane的宽度由父项VBox确定,而不是由TilePaneprefColumns属性确定。

javadoc of prefColumns

此值仅用于计算tilepane的优选尺寸和可能不反映的 列的实际数量,如果tilepane被调整大小的东西可能改变除了其首选 高度 宽度。

(有些由我定的文档的错误。)

您需要使用不调整TilePane父。 (VBox默认调整它的孩子。)使用VBox.setFillWidth来更改此行为:

root.setFillWidth(false);