如何更改单个条形的颜色 java fx [英] How to change color of a single bar java fx
本文介绍了如何更改单个条形的颜色 java fx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码,它生成从 0 到 10 的 10 个值的条形图.我想按如下方式更改条形的颜色
Here is my code which generates bar chart of 10 values from 0 to 10 . i want to change the color of bars as follows
if i>5 color==red如果 i>8 色==蓝色
if i>5 color==red if i>8 color==blue
所以最终输出将是 0-5(默认黄条)6-8(红条)9(蓝条)
so the final out will be 0-5(default yellow bars) 6-8(Red bars) 9(blue bar)
请帮助我..谢谢
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
颜色设置为不同的颜色.
The solution works by setting the bar's -fx-bar-fill
color to a different color based on the value of the bar's data.
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;");
}
}
}
});
这篇关于如何更改单个条形的颜色 java fx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文