我想更新JavaFX BarChart。我用这种方法初始化我的BarChart:
private void initFxComponents(String questionName){
Platform.runLater(() -> {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final BarChart<String, Number> barChart = new BarChart<>(xAxis,yAxis);
barChart.setTitle(questionName);
barChart.setLegendVisible(false);
xAxis.setLabel("Answer");
yAxis.setLabel("Number of times answered");
series = new Series();
int nbAnswersForProposal;
String proposal;
for(Proposal p : question.getListProposals()){
nbAnswersForProposal = Answers.getInstance().getNbAnswersForProposal(quiz.getId(), question.getId(), p.getId());
proposal = p.getProposal();
StringBuilder sb = new StringBuilder(proposal);
int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1)
sb.replace(i, i + 1, "\n");
series.getData().add(new Data(sb.toString(), nbAnswersForProposal));
}
Scene scene = new Scene(barChart,800,800);
barChart.getData().addAll(series);
fxPanel.setScene(scene);
});
}
我使用此方法更新数据:
public void updateData(){
Platform.runLater(() -> {
series.getData().clear();
int nbAnswersForProposal;
String proposal;
for(Proposal p : question.getListProposals()){
nbAnswersForProposal = Answers.getInstance().getNbAnswersForProposal(quiz.getId(), question.getId(), p.getId());
proposal = p.getProposal();
StringBuilder sb = new StringBuilder(proposal);
int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1)
sb.replace(i, i + 1, "\n");
series.getData().add(new Data(sb.toString(), nbAnswersForProposal));
}
});
}
但是当我更新数据时,BarChart错误并且无法正确显示数据。我想我没有做正确的事情来更新我的BarChart,任何人都可以帮助我吗? 谢谢!
答案 0 :(得分:1)
好的,我找到了解决问题的方法。显然,动画会导致数据不正确显示并打破自动调整大小。
所以只需添加:barChart.setAnimated(false);
你将不再拥有动画,但它将解决问题。
我也更新了这个:
private final Series series = new Series();
...
series.getData().add(new Data(sb.toString(), nbAnswersForProposal));
...
barChart.getData().addAll(series);
由此:
private final XYChart.Series<String, Number> series = new XYChart.Series<>();
...
series.getData().add(new XYChart.Data(sb.toString(), nbAnswersForProposal));
...
barChart.setData(FXCollections.observableArrayList(series));
public void updateData(){
// You need to run it in thread
Platform.runLater(() -> {
// Update chart's name
barChart.setTitle(questionName);
// Remove all data
series.getData().clear();
// Add as many data as you want
series.getData().add(new XYChart.Data("xData", yValue));
});
}
在我的情况下,我需要删除数据并添加新数据。但是,如果x值没有改变,你也可以更新值(y值)。
感谢Roland帮助我解答他的问题 JavaFX Chart Auto-Scaling Wrong with Low Numbers