gpt4 book ai didi

java - 为什么在将事件添加到每个饼图切片后,JavaFX PieChart 标签不显示? (Java 8)

转载 作者:行者123 更新时间:2023-12-02 13:10:54 26 4
gpt4 key购买 nike

我正在遵循本教程(底部称为“处理饼图的鼠标事件”的部分):

https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/pie-chart.htm

我的代码如下:

@FXML
public void initialize() {
pieChart.setTitle("Breakdown of Customers by City");
pieChart.setLegendSide(Side.LEFT);

final Task<ObservableList<PieChart.Data>> task = new NumClientsAtLocationTask(new CustomerAccountDaoSelect());
new Thread(task).start();
task.setOnSucceeded(ae -> {

pieChart.setData(task.getValue());

final Label caption = new Label("");
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");

for (final PieChart.Data data : pieChart.getData()) {
data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
ae2 -> {
caption.setTranslateX(ae2.getSceneX());
caption.setTranslateY(ae2.getSceneY());
caption.setText(String.valueOf(data.getPieValue()));
});
}
});

}


class NumClientsAtLocationTask extends Task<ObservableList<PieChart.Data>> {
private DaoSelect<CustomerAccount> customerAccountDaoSelect;

NumClientsAtLocationTask(DaoSelect<CustomerAccount> customerAccountDaoSelect) {
this.customerAccountDaoSelect = customerAccountDaoSelect;
}

@Override
protected ObservableList<PieChart.Data> call() throws Exception {
List<CustomerAccount> customerAccounts = customerAccountDaoSelect.select(RunListeners.FALSE);

Map<String, List<CustomerAccount>> customerMap =
customerAccounts
.stream()
.collect(Collectors.groupingBy(CustomerAccount::getCity));

int london = customerMap.get("London").size();
int phoenix = customerMap.get("Phoenix").size();
int newYork = customerMap.get("New York").size();

ObservableList<PieChart.Data> results = FXCollections.observableArrayList(
new PieChart.Data("London", london),
new PieChart.Data("Phoenix", phoenix),
new PieChart.Data("New York", newYork));

updateValue(results);
return results;
}
}

图表以其默认形式显示良好,但是当我在切片上单击鼠标时,标签不会出现。如果我将标签打印到控制台,它会显示正确的值,只是不会像教程中那样显示在屏幕上。有什么想法吗?

最佳答案

该示例/教程非常糟糕,并且省略了一个重要的细节。您需要先将Labelcaption”添加到Scene

如果您纯粹使用该教程中的示例代码,则需要包含 ((Group) scene.getRoot()).getChildren().add(caption);:

final Label caption = new Label("");
((Group) scene.getRoot()).getChildren().add(caption); // Add me
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");

for (final PieChart.Data data : chart.getData()) {
data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
caption.setTranslateX(e.getSceneX());
caption.setTranslateY(e.getSceneY());
caption.setText(String.valueOf(data.getPieValue()) + "%");
}
});
}

关于java - 为什么在将事件添加到每个饼图切片后,JavaFX PieChart 标签不显示? (Java 8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com