Skip to content

Instantly share code, notes, and snippets.

@TheItachiUchiha
Last active August 29, 2015 14:14
Show Gist options
  • Save TheItachiUchiha/298eba5a999e82ca2ddd to your computer and use it in GitHub Desktop.
Save TheItachiUchiha/298eba5a999e82ca2ddd to your computer and use it in GitHub Desktop.
CustomHBar
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class CustomHbar extends HBox {
private final Map<String, Double> map;
private final DoubleProperty length = new SimpleDoubleProperty();
public CustomHbar(Map<String, Double> map) {
this.map = map;
initialize();
}
private void initialize(){
Set<String> keys = map.keySet();
Double sum = sum(map.values());
int i=1;
for(String name : keys) {
CustomStackPane customStackPane = new CustomStackPane(name, map.get(name), sum, i++);
getChildren().add(customStackPane);
setHgrow(customStackPane, Priority.ALWAYS);
}
setSpacing(2);
setEffect(new DropShadow(10, Color.BLACK));
setPrefWidth(400);
length.bind(widthProperty());
}
private Double sum(Collection<Double> values){
Double temp = new Double(0.0);
for(Double value:values){
temp+=value;
}
return temp;
}
private class CustomStackPane extends StackPane{
private final Label label = new Label();
private final Rectangle rectangle = new Rectangle();
public CustomStackPane(String name, Double value, Double total, int color){
Double ratio = value/total;
init(name, ratio, color);
getChildren().addAll(rectangle, label);
}
private void init(String name, Double ratio, int color){
label.setText(name);
rectangle.widthProperty().bind(length.multiply(ratio));
rectangle.setHeight(20);
rectangle.setStyle("-fx-fill:CHART_COLOR_" + color + ";");
}
}
}
@TheItachiUchiha
Copy link
Author

A main method to test

import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
     Map<String, Double> map = new HashMap<String, Double>();
     map.put("Pass", 1125.0);
     map.put("Fail", 5454.0);
     map.put("Random", 3454.0);
     CustomHbar customHbar = new CustomHbar(map);
     Scene scene = new Scene(customHbar, 500, 500);
     primaryStage.setScene(scene);
         primaryStage.show();
    }
    public static void main(String[] args) {
    launch(args);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment