[英]How to change color of a single bar java fx
这是我的代码,它生成从 0 到 10 的 10 个值的条形图。 我想改变条形的颜色如下
if i>5 color==red if i>8 color==blue
所以最终输出将是 0-5(默认黄色条) 6-8(红色条) 9(蓝色条)
请帮助我..谢谢
public class BarChartSample extends Application {
@Override
public void start(Stage stage) {
stage.setTitle("Bar Chart Sample");
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final BarChart < String, Number > bc = new BarChart < String, Number > (xAxis, yAxis);
bc.setTitle("Country Summary");
xAxis.setLabel("bars");
yAxis.setLabel("Value");
XYChart.Series series1 = new XYChart.Series();
series1.setName("...");
for (int i = 0; i < 10; i++) {
//here i want to change color of bar if value of i is >5 than red if i>8 than blue
series1.getData().add(new XYChart.Data("Value", i));
}
}
public static void main(String[] args) {
launch(args);
}
}
我创建了一个示例解决方案。
该解决方案的工作原理是根据条形数据的值将条形的-fx-bar-fill
颜色设置为不同的颜色。
final XYChart.Data<String, Number> data = new XYChart.Data("Value " + i , i);
data.nodeProperty().addListener(new ChangeListener<Node>() {
@Override public void changed(ObservableValue<? extends Node> ov, Node oldNode, Node newNode) {
if (newNode != null) {
if (data.getYValue().intValue() > 8 ) {
newNode.setStyle("-fx-bar-fill: navy;");
} else if (data.getYValue().intValue() > 5 ) {
newNode.setStyle("-fx-bar-fill: firebrick;");
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.