2012-03-27 36 views

回答

8

一個例子將回答您的問題:

  • :(1)它使用綁定,連接面板尺寸與矩形大小
  • 爲(2)它增加了setOnMouseClick每個在lastOne字段中存儲點擊的矩形。
  • 爲(3)見setOnMouseClick()處理程序的代碼

    public class RectangleGrid extends Application { 
    
        private Rectangle lastOne; 
    
        public void start(Stage stage) throws Exception { 
        Pane root = new Pane(); 
    
        int grid_x = 7; //number of rows 
        int grid_y = 7; //number of columns 
    
        // this binding will find out which parameter is smaller: height or width 
        NumberBinding rectsAreaSize = Bindings.min(root.heightProperty(), root.widthProperty()); 
    
        for (int x = 0; x < grid_x; x++) { 
         for (int y = 0; y < grid_y; y++) { 
          Rectangle rectangle = new Rectangle(); 
          rectangle.setStroke(Color.WHITE); 
    
          rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() { 
           @Override 
           public void handle(MouseEvent t) { 
            if (lastOne != null) { 
             lastOne.setFill(Color.BLACK); 
            } 
            // remembering clicks 
            lastOne = (Rectangle) t.getSource(); 
            // updating fill 
            lastOne.setFill(Color.RED); 
           } 
          }); 
    
          // here we position rects (this depends on pane size as well) 
          rectangle.xProperty().bind(rectsAreaSize.multiply(x).divide(grid_x)); 
          rectangle.yProperty().bind(rectsAreaSize.multiply(y).divide(grid_y)); 
    
          // here we bind rectangle size to pane size 
          rectangle.heightProperty().bind(rectsAreaSize.divide(grid_x)); 
          rectangle.widthProperty().bind(rectangle.heightProperty()); 
    
          root.getChildren().add(rectangle); 
         } 
        } 
    
        stage.setScene(new Scene(root, 500, 500)); 
        stage.show(); 
        } 
    
        public static void main(String[] args) { launch(); } 
    } 
    
+0

非常感謝... :) – 2012-03-28 01:09:47

相關問題