JavaFx如何设置NumberAxis Cyclic?

时间:2017-08-27 10:53:42

标签: javafx

我需要创建一个X轴为角度的ScatterChart。

X轴需要具有以下值:

 try{

 Calendar cal = Calendar.getInstance();
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 cal.setTime(sdf.parse("2017-08-25 09:20:54"));

  Calendar calendar = Calendar.getInstance();
  long now = calendar.getTimeInMillis();
  long time = cal.getTimeInMillis();

  long diff = now - time;

  int seconds = (int) (diff / 1000) % 60 ;
  int minutes = (int) ((diff / (1000*60)) % 60);
  int hours   = (int) ((diff / (1000*60*60)) % 24);
  int days = (int) (diff / (1000*60*60*24));

  System.out.println(time + " " + now);
  System.out.println(hours + " hours ago");
  System.out.println(minutes + " minutes ago");
  System.out.println(seconds + " seconds ago");
  System.out.println(days + " days ago");


}catch(ParseException e){
     System.out.println(e.toString());
}

我可以创建像:

这样的axsis
[180, 225, 270, 315, 0, 45, 90, 135, 180]  (tickUnit = 45).

但它给了我:

NumberAxis(-180,180, 45)

如何使用tickUnit = 45从-180开始NumberAxis并最终结束180(当然使用Cyclic ...)

由于

1 个答案:

答案 0 :(得分:1)

您可以使用tickLabelFormatter更改标记的标记方式:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class CyclicChart extends Application {

    @Override
    public void start(Stage primaryStage) {
        NumberAxis xAxis = new NumberAxis(-180, 180, 45);
        NumberAxis yAxis = new NumberAxis(-1,1,0.1);
        ScatterChart<Number, Number> chart = new ScatterChart<>(xAxis, yAxis);

        xAxis.setTickLabelFormatter(new StringConverter<Number>() {

            @Override
            public String toString(Number object) {
                double value = object.doubleValue();
                if (value < 0) {
                    value = value + (1 + (int)(-value / 360)) * 360 ;
                }
                return String.format("%.1f", value % 360);
            }

            @Override
            public Number fromString(String string) {
                // Not used
                return null;
            }

        });

        Series<Number, Number> series = new Series<>();
        chart.getData().add(series);
        double min = xAxis.getLowerBound();
        double range = xAxis.getUpperBound() - min ;
        int numPoints = 90 ;
        for (int i = 0 ; i <= numPoints ; i++) {
            double a = min + i * range / numPoints ;
            series.getData().add(new Data<>(a, Math.sin(Math.toRadians(a))));
        }

        primaryStage.setScene(new Scene(chart, 800, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

请注意,图表中使用的实际值仍在[-180,180]范围内,但显示屏会强制它们显示在[0,360]范围内。