Fill/Padding space between 2 Labels with dots in GridPane (JavaFX)

1k views Asked by At

Starting point:

  • GridPane with 2 Columns
  • each Column has a Label

enter image description here


Like-to-have output:

  • space between the labels filled by dots

enter image description here

So far I have only come across String solutions in which the target length of the combined String is known. But this case doesn't do it for me because I need a solution which can also works when screen size changes and therefore the space between Labels do change dynamically. Could you guys please point me to the right direction?

1

There are 1 answers

1
fabian On

You could put the 2 Labels in a HBox with a Region in between them, set hgrow for the labels and the Region to NEVER and ALWAYS respectively and use a linear gradient as background for the region that draws half of it's size black and the other half transparent.

Example

// 20 px wide horizontal gradient alternating between black and transparent with immediate color switch
private static final Paint FILL = new LinearGradient(
        0, 0,
        10, 0,
        false,
        CycleMethod.REPEAT,
        new Stop(0, Color.BLACK),
        new Stop(0.5, Color.BLACK),
        new Stop(0.5, Color.TRANSPARENT)
);

// create background for regions
private static final Background BACKGROUND = new Background(new BackgroundFill(FILL, CornerRadii.EMPTY, Insets.EMPTY));

private static void addRow(Pane parent, String s1, String s2) {
    // create labels
    Label label1 = new Label(s2);
    Label label2 = new Label('['+s2+']');
    
    // create filler region with "stroke width" 2
    Region filler = new Region();
    filler.setPrefHeight(2);
    filler.setBackground(BACKGROUND);
    
    HBox hbox = new HBox(5, label1, filler, label2);
    hbox.setAlignment(Pos.CENTER);
    HBox.setHgrow(label1, Priority.NEVER);
    HBox.setHgrow(label2, Priority.NEVER);
    HBox.setHgrow(filler, Priority.ALWAYS);
    hbox.setFillHeight(false);
    
    parent.getChildren().add(hbox);
}

@Override
public void start(Stage primaryStage) {
    VBox root = new VBox();
    addRow(root, "JBoss", "DOWN");
    addRow(root, "GlassFish", "UP");
    addRow(root, "verylongprocessname", "UP");

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}

You could also use a border (top only) on the Region instead of using a background and do not set prefHeight. This would allow you to actually use dots instead of strokes, but since your picture shows strokes, I posted the background approach instead...