Issue
This is my code:
public class NewMain1 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
HBox root = new HBox();
ToolBar toolbar = new ToolBar();
toolbar.getItems().addAll(new TextField(), new Separator(), new Button("foo"), new Button("bar"));
root.getChildren().addAll(toolbar);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
}
And this is the result:
As you can see the distance between a text field and a separator (left margin) is less then the distance between the separator and a button (right margin).
Could anyone say how to decrease right margin that right margin to be equal to the left margin using CSS?
Solution
I checked in ScenicView and the line in the separator is rendered as a region with padding of 3px in each direction, so it makes the separator 6 pixels wide.
But the way it is rendered places the actual separator line in the left of the region.
You can adjust the line rendering by adjusting the the CSS rules for the line (you can find them in modena.css
in a jar file in your JavaFX distribution). But modifying the CSS rules for the separator is confusing and I don't recommend it.
Instead set a margin on the node to move it to the location you want (normally I wouldn't recommend such a hack, but in this case it is appropriate IMO).
Because ToolBar is internally represented as a HBox, you can use the HBox methods to set the margin on nodes in the ToolBar.
To add additional space to the left, so the line is centered in its display do this:
HBox.setMargin(sep, new Insets(0, 0, 0, 2.5));
OR, to remove space from the right, so the line is centered in its display do this:
HBox.setMargin(sep, new Insets(0, -2.5, 0, 0));
The margin values I provided are just examples. Adjust the values as per your requirements.
Example Code
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ToolBarApp extends Application {
@Override
public void start(Stage primaryStage) {
HBox root = new HBox();
ToolBar toolbar = new ToolBar();
Separator sep = new Separator();
toolbar.getItems().addAll(
new TextField(),
sep,
new Button("foo"),
new Button("bar")
);
HBox.setMargin(sep, new Insets(0, -2.5, 0, 0));
root.getChildren().addAll(
toolbar
);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Answered By - jewelsea
Answer Checked By - Cary Denson (JavaFixing Admin)