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



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

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

我已经向网格窗格添加了 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();
}
}

相关内容

  • 没有找到相关文章

最新更新