How in the StackPane can you get the number of the element on which the mouse is bent?
1 answer
Very simple. You need to add an event handler "moving the mouse over the component", or onMouseMoved. In the handler, access the collection of items in the StackPane, and call the indexOf method on the collection. Here is an example:
import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import java.util.ArrayList; public class Controller { @FXML private StackPane stackPane; @FXML public void initialize(){ ArrayList<Pos> pos = new ArrayList<>(); pos.add(Pos.TOP_CENTER); pos.add(Pos.CENTER); pos.add(Pos.BOTTOM_CENTER); for(int i = 0;i<3;i++){ Button btn = new Button(String.valueOf(i + 1)); btn.setOnMouseMoved(this::mouseDrag); StackPane.setAlignment(btn, pos.get(i)); stackPane.getChildren().add(btn); } } public void mouseDrag(MouseEvent mouseEvent) { Button btn = (Button)mouseEvent.getSource(); int index = stackPane.getChildren().indexOf(btn); System.out.println("Index of the element under the mouse: " + index); } }
- Thank! Is there a way to get the level of the object on which the mouse hovers? And after I do toFront (), I would like to bring it back (but not to the very end (toBack ()), but to its original place) - RedCape pm
- @RedCape if the answer helped you - mark it correctly so that other participants can take advantage of it. And for your next question, better issue a new question :) - Range
- I did the question) But something is not being answered ( - RedCape
- @RedCape I wrote you in that topic, look, maybe this will help. - Range
- Hi, you can see the latest topic, it seems everything is written correctly, but something does not work - RedCape
|