Live LineChart上的工具提示 [英] Tooltip on Live LineChart
问题描述
我找到了许多如何在LineChart上添加Tooltip的示例,但没有提供如何在Live LineChart上添加Tooltip的信息或示例。
I found many examples how to add Tooltip on a LineChart but no information or example how to add Tooltip on Live LineChart.
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;
public class MainApp extends Application
{
private static final int MAX_DATA_POINTS = 50;
private Series series;
private Series series2;
private int xSeriesData = 0;
private ConcurrentLinkedQueue<Number> dataQ = new ConcurrentLinkedQueue<Number>();
private ConcurrentLinkedQueue<Number> dataQ2 = new ConcurrentLinkedQueue<Number>();
private ExecutorService executor;
private AddToQueue addToQueue;
private NumberAxis xAxis;
private void init(Stage primaryStage)
{
xAxis = new NumberAxis(0, MAX_DATA_POINTS, MAX_DATA_POINTS / 10);
xAxis.setForceZeroInRange(false);
xAxis.setAutoRanging(false);
NumberAxis yAxis = new NumberAxis();
yAxis.setAutoRanging(true);
//-- Chart
final AreaChart<Number, Number> sc = new AreaChart<Number, Number>(xAxis, yAxis)
{
// Override to remove symbols on each data point
@Override
protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item)
{
}
};
sc.setAnimated(false);
sc.setId("liveAreaChart");
sc.setTitle("Animated Area Chart");
//-- Chart Series
series = new AreaChart.Series<Number, Number>();
series.setName("Area Chart Series");
series2 = new AreaChart.Series<Number, Number>();
series2.setName("Area Chart Series");
sc.getData().addAll(series, series2);
xAxis.setTickLabelsVisible(false);
xAxis.setTickMarkVisible(false);
xAxis.setMinorTickVisible(false);
primaryStage.setScene(new Scene(sc));
}
@Override
public void start(Stage primaryStage) throws Exception
{
init(primaryStage);
primaryStage.show();
//-- Prepare Executor Services
executor = Executors.newCachedThreadPool(new ThreadFactory()
{
@Override
public Thread newThread(Runnable r)
{
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
addToQueue = new AddToQueue();
executor.execute(addToQueue);
//-- Prepare Timeline
prepareTimeline();
}
public static void main(String[] args)
{
launch(args);
}
private class AddToQueue implements Runnable
{
@Override
public void run()
{
try
{
// add a item of random data to queue
dataQ.add(Math.random());
dataQ2.add(Math.random());
Thread.sleep(200);
executor.execute(this);
}
catch (InterruptedException ex)
{
Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//-- Timeline gets called in the JavaFX Main thread
private void prepareTimeline()
{
// Every frame to take any data from queue and add to chart
new AnimationTimer()
{
@Override
public void handle(long now)
{
addDataToSeries();
}
}.start();
}
private void addDataToSeries()
{
for (int i = 0; i < 20; i++)
{ //-- add 20 numbers to the plot+
if (dataQ.isEmpty())
break;
Data data = new AreaChart.Data(xSeriesData++, dataQ.remove());
series.getData().add(data);
data.nodeProperty().addListener(new ChangeListener<Node>()
{
@Override
public void changed(ObservableValue<? extends Node> arg0, Node arg1,
Node arg2)
{
Tooltip t = new Tooltip(data.getYValue().toString() + '\n' + data.getXValue());
Tooltip.install(arg2, t);
data.nodeProperty().removeListener(this);
}
});
if (dataQ2.isEmpty())
break;
series2.getData().add(new AreaChart.Data(xSeriesData, dataQ2.remove()));
}
// remove points to keep us at no more than MAX_DATA_POINTS
if (series.getData().size() > MAX_DATA_POINTS)
{
series.getData().remove(0, series.getData().size() - MAX_DATA_POINTS);
}
// remove points to keep us at no more than MAX_DATA_POINTS
if (series2.getData().size() > MAX_DATA_POINTS)
{
series2.getData().remove(0, series2.getData().size() - MAX_DATA_POINTS);
}
// update
xAxis.setLowerBound(xSeriesData - MAX_DATA_POINTS);
xAxis.setUpperBound(xSeriesData - 1);
}
}
这是我想要创建的结果:
This is the result that I would like to create:
如果可能的话我设置setCreateSymbols(false);
If possible I to set setCreateSymbols(false);
推荐答案
首先,使用常规 AreaChart
而不是您正在使用的匿名子类(即不要覆盖 dataAddedItem(...)
方法) 。如果没有数据点存在,那么该方法会创建一个显示数据点的默认节点(这很大程度上违反了将数据与表示分离,imho,但我们无能为力......);你显然需要一个图形来附加工具提示。
First, use a regular AreaChart
instead of the anonymous subclass you are using (i.e. don't override the dataAddedItem(...)
method). That method creates a default node to display for the data point if none already exists (this is a huge violation of separating data from presentation, imho, but there's nothing we can do about that...); you obviously need a graphic there to attach the tooltip to.
一旦数据点有一个节点,你就不需要听取这些变化,所以在你的 addDataToSeries()
方法,删除监听器,只需将其替换为
Once the data point has a node, you don't need to listen to the changes, so in your addDataToSeries()
method, remove the listener and just replace it with
Tooltip t = new Tooltip(data.getYValue().toString() + '\n' + data.getXValue());
Tooltip.install(data.getNode(), t);
或者,只需创建自己的图形,附加工具提示,并将其传递给 data.setNode(...);
。
Or, just create your own graphic, attach a tooltip to it, and pass it to data.setNode(...);
.
您仍然会遇到一般性问题;当一切以每秒5个单位飞行时,我看不到用户如何将鼠标悬停在图表中的数据点上。即使他们可以,当工具提示出现时,点数会移动,因此值不正确...
You will still have a general usability problem; I don't see how the user is going to hover over a data point in the chart when everything is flying by at 5 units per second. And even if they could, by the time the tooltip appeared the points would have moved, so the values would be incorrect...
更新:
为了好玩,我尝试了这个:
Just for fun, I tried this:
ObjectProperty<Point2D> mouseLocationInScene = new SimpleObjectProperty<>();
Tooltip tooltip = new Tooltip();
sc.addEventHandler(MouseEvent.MOUSE_MOVED, evt -> {
if (! tooltip.isShowing()) {
mouseLocationInScene.set(new Point2D(evt.getSceneX(), evt.getSceneY()));
}
});
tooltip.textProperty().bind(Bindings.createStringBinding(() -> {
if (mouseLocationInScene.isNull().get()) {
return "" ;
}
double xInXAxis = xAxis.sceneToLocal(mouseLocationInScene.get()).getX() ;
double x = xAxis.getValueForDisplay(xInXAxis).doubleValue();
double yInYAxis = yAxis.sceneToLocal(mouseLocationInScene.get()).getY() ;
double y = yAxis.getValueForDisplay(yInYAxis).doubleValue() ;
return String.format("[%.3f, %.3f]", x, y);
}, mouseLocationInScene, xAxis.lowerBoundProperty(), xAxis.upperBoundProperty(),
yAxis.lowerBoundProperty(), yAxis.upperBoundProperty()));
Tooltip.install(sc, tooltip);
这会在图表上设置一个工具提示,在您移动鼠标时以及在下方滚动图表时更新这两个工具提示。这结合了这个问题和< a href =https://stackoverflow.com/questions/28585330/tooltip-how-to-get-mouse-coordinates-that-triggered-the-tip>这个。
This sets a tooltip on the chart that updates both as you move the mouse and as the chart scrolls below. This combines ideas from this question and this one.
这篇关于Live LineChart上的工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!