如何在javafx中使用鼠标绘制选定的gridpane范围

时间:2014-01-09 08:58:42

标签: graphics javafx-2 gridpanel

我想选择几个网格窗格并改变它们的颜色。

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

1 个答案:

答案 0 :(得分:1)

我在网格窗格中添加了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();
}
}