sillyPin
sillyPin

Reputation: 35

How to set colours of Segmented Bar Segments in JavaFX?

How do I set the colur of specific segments of a segmented bar in JavafX - which is from ControlsFX?

https://javadoc.io/static/org.controlsfx/controlsfx/8.40.16/org/controlsfx/control/SegmentedBar.html

So if I very basically constructed and set two segments as below, how would I set them as different colours?

@FXML SegmentedBar segments;

public void setSegments() {
segments.getSegments().addAll(
     new SegmentedBar.Segment(10, "10"),
     new SegmentedBar.Segment(90, "90"));
}

The .setStyle() method, which I've seen used elsewhere as a solution, seems to only work for the Segmented Bar object itself, not the individual segments. So I'm at a loss.

Upvotes: 1

Views: 169

Answers (1)

James_D
James_D

Reputation: 209418

Use the segmentViewFactory to style the SegmentView used to display each Segment:

import org.controlsfx.control.SegmentedBar;
import org.controlsfx.control.SegmentedBar.Segment;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;



public class App extends Application {

    @Override
    public void start(Stage stage) {
        SegmentedBar<Segment> segments = new SegmentedBar<>();
        segments.setOrientation(Orientation.HORIZONTAL);
        segments.getSegments().addAll(
                 new SegmentedBar.Segment(10, "10"),
                 new SegmentedBar.Segment(90, "90")     
        );
        segments.setSegmentViewFactory(segment -> {
            SegmentedBar<Segment>.SegmentView view = segments.new SegmentView(segment);
            String color = segment.getValue() < 50 ? "#66C2A5" : "#FC8D62" ;
            view.setStyle("-fx-background-color: "+color);
            return view ;
        });
        
        BorderPane root = new BorderPane(segments);
        root.setPadding(new Insets(10));
        Scene scene = new Scene(root, 800, 500);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

enter image description here

Upvotes: 2

Related Questions