Graphes linéaires animés avec fonctions graphiques linéaires primitives Java

StackOverflow https://stackoverflow.com/questions/1603820

  •  05-07-2019
  •  | 
  •  

Question

Dans le but d'en apprendre davantage sur les applets et Java, j'essaie de créer des applets wave en traçant des lignes (drawLine) et des graphes linéaires animés.

Je peux très bien créer un graphique statique. Toutefois, je suis aux prises avec l’aspect animé du graphique: les axes du graphique doivent se déplacer de gauche à droite, de plus en plus grands et de plus en plus grands que 0.

Mon problème est de traduire mes besoins en solution. Quelqu'un peut-il me donner des indications sur mon problème?

J'ai un tableau multidimensionnel indexé par des points contenant les x et y d'un point particulier. J'ai essayé de modifier ma fonction de rendu pour diminuer les X afin de donner l'impression que la fonction se déplace vers la gauche, mais cela ne fonctionne pas correctement.

Quelle approche est-ce que je cherche à adopter? En quoi mon approche sera-t-elle différente si les valeurs de Y pouvaient changer en raison d'une action de l'utilisateur ou de l'ajout de données?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

/**
 * A graph that should in the future represent a wave according to my inputs
 * 
 * @authorImprofane
 * @version 1
 */
public class Graph extends JFrame
{
    private InnerGraph inner;

    private int width;
    private Random RNG;
    private int height;
    private int[][] series;

    private int xoffset;
    int prevx = 0;
    int prevy = 0;



    /**
     * Constructor for objects of class Graph
     */
    public Graph(int width, int height) throws InterruptedException
    {
         RNG = new Random();
         setTitle(" Graph");

         series = new int[width][2];

         this.width = width;
         this.height = height;
         inner = new InnerGraph(width, height);

         add(inner, BorderLayout.CENTER);

         setVisible(true);
         inner.preparePaint();
         pack();
         updateGraph();
    }

    public static void main(String[] args) throws InterruptedException
    {
        new Graph(300, 300);
    }

    public void updateGraph() throws InterruptedException
    {   

        // virtual x is how far along on the x axis we are, I ignore the 'real' X axis
        int vx = 0;
        int point = 0;
        int xdecay = 0;
        int inc = 5;

        // how many times we need to plot a point
        int points = (int) java.lang.Math.floor( width / inc );
            System.out.println(points);
            inner.preparePaint();
            // draw all points to graph

            // make some junk data, a saw like graph
            for (vx = 0 ; vx < points ; vx++) {
                series[vx] = new int[] { vx*inc, ( (vx*inc) % 120 ) };
            }

            Thread.sleep(150);
            int n = 5;

        while(n > 0) {
            System.out.println(xdecay);
            inner.preparePaint();
                for (vx = 0 ; vx < points ; vx++) {
                    inner.updateSeries(vx, xdecay);

                    inner.repaint();
                    Thread.sleep(50);
                }
                xdecay += inc;

                // shift the data points to the left
                int[][] nseries = new int[points][2];
                // System.arraycopy(series, 1, nseries, 0, points-1);
                n--;
            }

    }

    public class InnerGraph extends JPanel
    {
        private Graphics g;
        private Image img;

        private int gwidth;
        private int gheight;

        Dimension size;

        public InnerGraph(int width, int height)
        {
            gwidth = width;
            gheight = height;
            size = new Dimension(1, 1);


        }

        /**
         * Try make panel the requested size.
         */
        public Dimension getPreferredSize()
        {
            return new Dimension(gwidth, gheight);
        }

        /**
         * Create an image and graphics context
         * 
         */

        public void preparePaint()
        {          
            size = getSize();
            img = inner.createImage( (size.width | gwidth), (size.height | gheight) );
            g = img.getGraphics();


        }

        /**
         * Draw a point to the chart given the point to use and the decay. 
         * Yes this is bad coding style until I work out the mathematics needed
         * to do what I want.
         */

        public void updateSeries(int point, int decay)
        {
            g.setColor(Color.blue);
            int nx = series[point][0];

            series[point][0] -= decay;
            if ( point-1 >= 0 ) {
                series[point-1][0] -= decay;
            }

            int ny = series[point][1];
            prevx -= decay;

            g.drawLine(prevx-decay, prevy, nx-decay, ny );         
            prevx = nx-decay;
            prevy = ny;
        }


        public void paintComponent(Graphics g)
        {
                    g.drawImage(img, 0, 0, null);
}
    }

}
Était-ce utile?

La solution

Tout d'abord, il semble que vous soustrayiez trop souvent la décroissance dans la méthode updateSeries. Vous trouverez ci-dessous une nouvelle version de cette méthode.

public void updateSeries(int point, int decay)
    {

        g.setColor(Color.blue);
        int nx = series[point][0];

        series[point][0] -= decay;
        if ( point-1 >= 0 ) {
            series[point-1][0] -= decay;
        }

        int ny = series[point][1];
    //    prevx -= decay;

    //    g.drawLine(prevx-decay, prevy, nx-decay, ny );         
    g.drawLine(prevx, prevy, nx-decay, ny );     
        prevx = nx-decay;
        prevy = ny;
    }

Avec ces modifications, les lignes dessinent mieux, mais elles dessinent si lentement que l’animation est difficile à voir. Vous aurez probablement besoin de créer un nouveau graphique et de tout échanger pour ne pas avoir à regarder chaque segment de ligne dessiné.

Autres conseils

Pour un débutant, vous pouvez consulter l'exemple suivant (et ceux qui s'y rapportent)

Graphique de défilement @ java2s.com

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top