2014-01-09 16 views
0

我想選擇幾個網格單元並更改它們的顏色。如何在javafx中用鼠標繪製所選的網格範圍

 myGridPane.getChildren().get(indexer).setOnDragEntered(new EventHandler<DragEvent>(){ 
      @Override 
      public void handle(DragEvent t) { 
       myGridPane.getChildren().get(ci).setStyle("-fx-background-color:yellow;"); 
      }     
     }); 
+0

您想在GridPane單元格發生拖動事件時突出顯示單元格嗎? – Aspirant

+0

我想點擊鼠標,當它釋放它,選定的單元格給一些顏色 – user2858883

+0

你打算怎麼*給一些顏色*? *顏色選擇器會彈出嗎? – Aspirant

回答

1

我在gridpane中添加了3個標籤,並且爲每個標籤添加了一個點擊處理程序。看看這是你想要的。

import javafx.application.Application; 
import javafx.event.EventHandler; 
import javafx.geometry.HPos; 
import javafx.geometry.VPos; 
import javafx.scene.Node; 
import javafx.scene.Scene; 
import javafx.scene.control.Control; 
import javafx.scene.control.Label; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.ColumnConstraints; 
import javafx.scene.layout.GridPane; 
import javafx.scene.layout.RowConstraints; 
import javafx.scene.layout.StackPane; 
import javafx.stage.Stage; 

public class GridPaneStyle extends Application 
{ 
@Override 
public void start(final Stage stage) 
{ 
    // create a grid with some sample data. 
    GridPane grid = new GridPane(); 

    final Label l1 = new Label("1"); 
    final Label l2 = new Label("2"); 
    final Label l3 = new Label("3"); 


    l1.setOnMouseClicked(new EventHandler<MouseEvent>() 
    { 

     @Override 
     public void handle(MouseEvent arg0) 
     { 
      l1.setStyle("-fx-background-color:yellow;"); 

     } 
    }); 

    l2.setOnMouseClicked(new EventHandler<MouseEvent>() 
    { 

     @Override 
     public void handle(MouseEvent arg0) 
     { 
      l2.setStyle("-fx-background-color:yellow;"); 

     } 
    }); 


    l3.setOnMouseClicked(new EventHandler<MouseEvent>() 
    { 

     @Override 
     public void handle(MouseEvent arg0) 
     { 
      l3.setStyle("-fx-background-color:yellow;"); 

     } 
    }); 


    grid.addRow(0, l1, l2, l3); 

    for (Node n : grid.getChildren()) 
    { 
     Control control = (Control) n; 
     control.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE); 
     control.setStyle("-fx-background-color: tomato; -fx-alignment: center;"); 
    } 

    grid.setStyle("-fx-background-color: palegreen; -fx-padding: 2; -fx-hgap: 2; -fx-vgap: 2;"); 
    grid.setSnapToPixel(false); 

    ColumnConstraints oneThird = new ColumnConstraints(); 
    oneThird.setPercentWidth(100/3.0); 
    oneThird.setHalignment(HPos.CENTER); 
    grid.getColumnConstraints().addAll(oneThird, oneThird, oneThird); 
    RowConstraints oneHalf = new RowConstraints(); 
    oneHalf.setPercentHeight(100/2.0); 
    oneHalf.setValignment(VPos.CENTER); 
    grid.getRowConstraints().addAll(oneHalf, oneHalf); 

    StackPane layout = new StackPane(); 
    layout.setStyle("-fx-background-color: white;"); 
    layout.getChildren().addAll(grid); 
    stage.setScene(new Scene(layout, 600, 400)); 
    stage.show(); 

} 

public static void main(String[] args) 
{ 
    launch(); 
} 
} 
相關問題