如何在javafx中用鼠标绘制选定的网格窗格范围
Posted
技术标签:
【中文标题】如何在javafx中用鼠标绘制选定的网格窗格范围【英文标题】:How to paint the selected gridpane range with mouse in javafx 【发布时间】:2014-01-09 08:58:41 【问题描述】:我想选择几个网格单元格并更改它们的颜色。
myGridPane.getChildren().get(indexer).setOnDragEntered(new EventHandler<DragEvent>()
@Override
public void handle(DragEvent t)
myGridPane.getChildren().get(ci).setStyle("-fx-background-color:yellow;");
);
【问题讨论】:
GridPane
单元格上发生拖动事件时是否要突出显示单元格?
我想点击鼠标,当释放它时,选定的单元格会给出一些颜色
你打算如何上色? 颜色选择器会弹出吗?
【参考方案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();
【讨论】:
以上是关于如何在javafx中用鼠标绘制选定的网格窗格范围的主要内容,如果未能解决你的问题,请参考以下文章