我想创建带有标题的饼图。当我将鼠标移到饼图上时,文本显示非常流畅。
public void naiveAddData(String name, double value)
{
pieChartData.add(new Data(name, value));
caption = new Label();
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");
for (final Data data : chart.getData())
{
data.getNode().addEventHandler(MouseEvent.MOUSE_MOVED,
new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
caption.setTranslateX(e.getSceneX() + 15);
caption.setTranslateY(e.getSceneY());
caption.setText(String.valueOf(data.getPieValue()) + "%");
}
});
}
}
但是当我将鼠标移到饼图外时,标题仍然存在。它没有删除。我怎么解决这个问题?
P.S我设法以这种方式解决问题:
data.getNode().addEventHandler(MouseEvent.MOUSE_MOVED,
new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
caption.setTranslateX(e.getSceneX() + 15);
caption.setTranslateY(e.getSceneY());
caption.setText(String.valueOf(data.getPieValue()) + "%");
caption.setVisible(true);
}
});
data.getNode().addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
caption.setVisible(false);
}
});
}
有没有更好的解决方案?
答案 0 :(得分:4)
如果您拥有标题的父级,则可以在鼠标退出时将其从父级删除,并在鼠标输入时再次添加。
Parent captionparent = ...
...
data.getNode().addEventHandler(MouseEvent.MOUSE_EXITED,
new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
captionparent.getChildren().remove(caption);
}
});
答案 1 :(得分:1)
以下是使用工具提示的完整示例。
public class ChartingMain extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
PieChart pc = new PieChart();
pc.setTitle("Most popular programming languages");
ObservableList<PieChart.Data> pcdata = FXCollections.<PieChart.Data>observableArrayList();
pcdata.add(new PieChart.Data("C#", 20d));
pcdata.add(new PieChart.Data("Java",800d));
pcdata.add(new PieChart.Data("C/C++", 400d));
final double total = 20d + 800d + 400d;
pc.dataProperty().set(pcdata);
stage.setScene(new Scene(pc));
stage.show();
for(PieChart.Data data : pc.getData()){
final Tooltip t = new Tooltip(data.getName() + " : " + new DecimalFormat("#.##").format((data.getPieValue() / total) * 100) + " %");
data.getNode().setOnMouseEntered(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent me) {
if(me.getSource() instanceof Node){
Node sender = (Node) me.getSource();
Tooltip.install(sender, t);
sender.setEffect(new Glow(0.5));
}
}});
data.getNode().setOnMouseExited(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent me) {
if(me.getSource() instanceof Node){
Node sender = (Node) me.getSource();
sender.setEffect(null);
t.hide();
}
}});
}
}
}