I'm having trouble with the following code. My Box
and border
does not want to center. It keeps reverting to the top left corner. I need it to snap to the center when running the program. I'm new to programming so the issue might be something simple. I have also tried shifting by the width
of the border using the setTranslateX
and setTranslateY
methods. This causes the boxPane
to be centered in the StackPane
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.input.ScrollEvent;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX Movable Box with Border and Grid");
int gridSize = 28;
double boxSize = 500.0; // size of the box
double borderWidth = 2.0; // width of the border
double cellSize = boxSize / gridSize; // size of each cell
Pane grid = new Pane();
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
Rectangle cell = new Rectangle(cellSize, cellSize);
cell.setFill(Color.WHITE);
cell.setStroke(Color.BLACK);
cell.setStrokeWidth(0.5);
cell.setX(j * cellSize + borderWidth / 2);
cell.setY(i * cellSize + borderWidth / 2);
grid.getChildren().add(cell);
}
}
// Create a border around the grid
Rectangle border = new Rectangle(boxSize + borderWidth, boxSize + borderWidth);
border.setFill(Color.TRANSPARENT);
border.setStroke(Color.BLACK);
border.setStrokeWidth(borderWidth);
border.setX(borderWidth / 2);
border.setY(borderWidth / 2);
Pane boxPane = new Pane();
boxPane.getChildren().addAll(border, grid);
StackPane root = new StackPane();
root.getChildren().add(boxPane);
Scene scene = new Scene(root, 700, 700);
scene.setOnScroll((ScrollEvent event) -> {
double zoomFactor = 1.05;
double deltaY = event.getDeltaY();
if (deltaY < 0){
zoomFactor = 2 - zoomFactor;
}
boxPane.setScaleX(boxPane.getScaleX() * zoomFactor);
boxPane.setScaleY(boxPane.getScaleY() * zoomFactor);
event.consume();
});
boxPane.setOnMouseDragged(event -> {
double newX = event.getSceneX() - boxSize / 2;
double newY = event.getSceneY() - boxSize / 2;
boxPane.setTranslateX(newX);
boxPane.setTranslateY(newY);
});
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I tried changing the box
and scene
size