我尝试为 JavaFX BarChart 实现向左拖动和向右拖动功能。当我在 x 轴数据系列的末尾添加一个项目并在开头删除一个项目时,左拖动功能可以正常工作。
但是,向右拖动功能无法按预期工作。它应该在 x 轴系列的开头添加一个项目并在末尾删除一个项目。删除工作正常,但添加操作导致项目被添加到条形图的末尾而不是开头。
我怀疑它与使用 CategoryAxis 有关,它不承认需要以排序方式从 ObservableList 更新 BarChart(即使我可以看到该项目被添加到底层 ObservableList 的开头)。
另外,请让我知道是否有更好的方法来实现拖动操作。
下面是重现问题的完整应用程序。
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class BarchartProblem extends Application {
private static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private double dragStartX = 0;
private long minTime;
private long maxTime;
@FXML
private BarChart<String,Number> histogramBarChart;
@Override
public void start(Stage primaryStage) {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setLabel("Time");
yAxis.setLabel("Entries");
histogramBarChart = new BarChart<String, Number>(xAxis, yAxis);
final XYChart.Series series1 = new XYChart.Series();
histogramBarChart.setLegendVisible(false);
histogramBarChart.getData().addAll(series1);
histogramBarChart.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println(mouseEvent);
dragStartX = mouseEvent.getX();
}
});
histogramBarChart.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if (dragStartX > mouseEvent.getX()) {
XYChart.Series series = histogramBarChart.getData().get(0);
minTime += 60000;
maxTime += 60000;
series.getData().add(new XYChart.Data(dateFormat.format(new Date(maxTime)), 0));
series.getData().remove(0);
System.out.println("Drag Left");
} else if (dragStartX < mouseEvent.getX()) {
XYChart.Series series = histogramBarChart.getData().get(0);
minTime -= 60000;
maxTime -= 60000;
series.getData().add(0, new XYChart.Data(dateFormat.format(new Date(minTime)), 0));
series.getData().remove(series.getData().size()-1);
System.out.println("Drag Right");
}
}
});
final long currentTime = System.currentTimeMillis();
minTime = currentTime-60000*30;
maxTime = currentTime;
for (long i = minTime; i <= maxTime; i += 60000) {
series1.getData().add(new XYChart.Data(dateFormat.format(new Date(i)), Math.random()*500));
}
StackPane root = new StackPane();
root.getChildren().add(histogramBarChart);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("BarChart Problem");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}