I am trying to display the gridlines of a GridPane Scene in JavaFX, but they aren't being displayed despite calling setGridLinesVisible(true)
. What am I doing wrong?
I want to display the gridlines on my program's main menu, so I can tell where to place nodes on it. Unfortunately, when I run the program all that is displayed is a blank screen with a single button.
My MainMenu Class:
package screens;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
/**
* Creates the main menu Pane object and returns it.
* @author LuminousNutria
*/
public class MainMenu {
public MainMenu() {}
public Pane getPane() {
GridPane grid = new GridPane();
grid.setGridLinesVisible(true);
Button bttn = new Button("button");
grid.add(bttn, 2, 2);
return grid;
}
}
My Main Class:
package mainPackage;
import screens.*;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
/**
* Displays the Pane.
* @author LuminousNutria
*/
public class Main extends Application {
// create main menu Pane
private Pane mainMenu = new MainMenu().getPane();
// create Scene
private Scene scene = new Scene(mainMenu, 1600, 900);
@Override
public void start(Stage stage) {
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This is Displayed:
JavaFX's GridPane class will only create as many points as is defined by the programmer when they set the position of an object on the grid.
For example, if an object is added to the grid with the x and y positions both equal to 0, then the grid will only have one (x, y) position, that being, (0, 0).
Also, even if the grid has many positions, unless the programmer sets the HGap
and Vgap
grid attributes, all of the "positions" of the grid, will be on the same point in the window created by the program.
The issue was that I hadn't adjusted the HGap
and VGap
attributes, so the entire grid was clustered on just one point in the window. This made it impossible to see any lines.
Replacing the getPane()
method with the below code allowed me to see the grid lines.
public Pane getPane() {
GridPane grid = new GridPane();
grid.setGridLinesVisible(true);
grid.setVgap(8);
grid.setHgap(8);
Button btn = new Button("button");
grid.add(btn, 5, 5);
return grid;
}
This is what was displayed once I had fixed my program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With