【发布时间】:2020-09-02 01:22:35
【问题描述】:
我是 Java 新手,我正在尝试创建一个实时 javaFX 条形图,它显示每个条形顶部的更新值。 我得到了这个每秒更新的条形图。如何使用此图表在每个条形顶部添加值。网上还有其他例子,但与此代码上的实时条形图不兼容。我怎样才能在每个栏中添加文本。谢谢
import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javafx.application.Application;
import javafx.application.Platform;
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.stage.Stage;
public class App extends Application {
private ScheduledExecutorService scheduledExecutorService;
final static String austria = "Austria";
final static String brazil = "Brazil";
final static String france = "France";
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Realtime Bar Chart Demo");
//defining the axes
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
xAxis.setAnimated(false);
yAxis.setAnimated(false);
//creating the bar chart with two axis
final BarChart<String,Number> bc = new BarChart<>(xAxis,yAxis);
bc.setAnimated(false);
bc.setTitle("Country Summary");
xAxis.setLabel("Country");
yAxis.setLabel("Value");
//defining a series to display data
XYChart.Series<String, Number> seriesA = new XYChart.Series<>();
seriesA.setName("Austra");
XYChart.Series<String, Number> seriesB = new XYChart.Series<>();
seriesB.setName("Brazil");
XYChart.Series<String, Number> seriesC = new XYChart.Series<>();
seriesC.setName("France");
// add series to chart
bc.getData().add(seriesA);
bc.getData().add(seriesB);
bc.getData().add(seriesC);
// setup scene
Scene scene = new Scene(bc, 800, 600);
primaryStage.setScene(scene);
// show the stage
primaryStage.show();
// setup a scheduled executor to periodically put data into the chart
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// input data onto graph per second
scheduledExecutorService.scheduleAtFixedRate(() -> {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
int secondA = cal.get(Calendar.SECOND);
int secondB = secondA + 27;
int secondC = secondA + 14;
// Update the chart
Platform.runLater(() -> {
// input realtime data number
seriesA.getData().add(new XYChart.Data<>(austria, secondA));
seriesB.getData().add(new XYChart.Data<>(brazil, secondB));
seriesC.getData().add(new XYChart.Data<>(france, secondC));
});
}, 0, 1, TimeUnit.SECONDS);
}
@Override
public void stop() throws Exception {
super.stop();
scheduledExecutorService.shutdownNow();
}
}
【问题讨论】:
-
请发帖minimal reproducible example。发布的代码无法编译。
-
我更新了代码,现在应该可以编译了。
-
你测试了吗?
Austria是否编译?Calendar.SECONDS编译吗?您要求这里的人们自愿解决您的问题,您应该让他们尽可能轻松地解决问题。 -
在我的电脑上它正在编译和更新数据。我复制了一份到我的手机上,因为我有一段时间不在家。我是否还必须包括进口?
-
hmm .. 没有看到 在每个栏的顶部显示更新值的任何代码 - 静态执行(或单击按钮),然后继续执行它来自后台线程。