Issue
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.
Solution
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();
}
}
Answered By - James_D
Answer Checked By - Timothy Miller (JavaFixing Admin)