In javaFX, there is a toFront () function that moves an object forward, and if there is a function that returns it back (toBack will not work because it moves to the very end)
1 answer
I researched your problem a bit, and there is some success. Having studied the documentation at my leisure, I did not find the method responsible for returning to the opposite position. In this regard, two methods that perform your task were invented quickly:
- Memorizing the position and when returning the shift of all elements previously standing for the current element.
- Memorizing the position and deletion with insertion from the collection of items in the panel.
I did not implement the first method, it is not very beautiful, and, in theory, when using so many calls toFront (), optimization will limp (if you have many elements in the collection). But the second method was implemented. It is simple, and in theory, it will not be too heavy to load the system, since the collection of elements in the StackPane is an ObservableList based on a sheet. The insert will be carried out quickly enough (I can be mistaken). The code is similar to the listing from the previous post. Enjoy using:
import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; public class Controller { @FXML private StackPane stackPane; @FXML public void initialize(){ for(int i = 5;i>0;i--){ int pow = i * 10; StringBuilder res = new StringBuilder(); for(int j = 0;j<pow;j++){ res.append(i); } Button btn = new Button(res.toString()); btn.setOnMouseMoved(this::mouseDrag); btn.setOnMouseClicked(this::mouseClick); 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); } public void mouseClick(MouseEvent mouseEvent){ Button btn = (Button)mouseEvent.getSource(); int index = -1; if(btn.getUserData() == null) { index = stackPane.getChildren().indexOf(btn); btn.setUserData(index); btn.toFront(); System.out.println("Btn to front"); } else { index = (int)btn.getUserData(); stackPane.getChildren().remove(btn); stackPane.getChildren().add(index, btn); btn.setUserData(null); System.out.println("Btn to back position"); } } } The code is tested; when the button is pressed, it is sent to the very top of the z - sequence, and when pressed again, it goes back to its place.