How to reinit the NumberAxis and move to next value in JavaFX LineChart?

孤人 提交于 2019-12-13 03:47:54

问题


I am currently trying to create a chart, which allows me to restart the x-axis and continue drawing. The axis range is 0-100, but when the graph reaches 100 need the following values is again 0. But what makes the chart is to be returned to the initial zero.

in the next two picture I show how to work the chart currently.

what makes the chart is to be returned to the initial zero and continue.

I need something like this:

Thank you very much for your help!!


回答1:


You can utilize the axis.setTickLabelFormatter() to format tick labels:

public class TickLabelFormatterDemo extends Application
{

    private static final int RANGE = 100;
    private int last_X_Axis_Val = 20;


    @Override
    public void start( Stage stage )
    {
        stage.setTitle( "Sample" );

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setForceZeroInRange( false);
        xAxis.setTickLabelFormatter( new StringConverter<Number>()
        {

            @Override
            public String toString( Number object )
            {
                int i = object.intValue() % RANGE;
                return String.valueOf( i == 0 ? RANGE : i );
            }

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

        final LineChart<Number, Number> lineChart
                = new LineChart<>( xAxis, yAxis );

        lineChart.setTitle( "Monitoring" );
        XYChart.Series series = new XYChart.Series();
        series.setName( "Values" );

        Random random = new Random();

        Timeline timeline = new Timeline( new KeyFrame( Duration.seconds( 2 ), new EventHandler<ActionEvent>()
        {
            @Override
            public void handle( ActionEvent event )
            {
                if ( series.getData().size() > 5 )
                {
                    series.getData().remove( 0 );
                }
                series.getData().add( new XYChart.Data( last_X_Axis_Val, random.nextInt( 50 ) ) );
                last_X_Axis_Val += 20;
            }
        } ) );
        timeline.setCycleCount( Timeline.INDEFINITE );
        timeline.play();

        Scene scene = new Scene( lineChart, 800, 600 );
        lineChart.getData().add( series );

        stage.setScene( scene );
        stage.show();
    }


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

}


来源:https://stackoverflow.com/questions/29622202/how-to-reinit-the-numberaxis-and-move-to-next-value-in-javafx-linechart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!