Search code examples
javaarraysswingawtpaint

Zero values in the array in the method paint


I would like to make a graphical representation of the audio signal. I have a problem with entering data array to the method paint (Graphics g). Data entered in the method setData(int intValue) works fine. But if I want to print a data array in the method paint() I have zero values. Why?

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class MyPlotter extends JPanel{
    int width = 320;
    int height = 130;
    int frameSize;
    int[] data;

public MyPlotter(int fSize){
    setSize(width,height);      
    setPreferredSize(this.getSize());
    this.frameSize = fSize;
    data = new int[fSize+1];
} 


public void setData(int[] intValue){
    data = intValue;

// this works fine:
        for (int i=0; i<440; i++)
            System.out.println("setData "+data[i]);

    repaint();
}

public void paint (Graphics g){ 

   // some code:
   // g.drawLine(...)
   // g.setColor(...)
   // etc...    

 for (int i = 0; i< frameSize-1;i++)
    { 
     //ZERO values:
     System.out.println("paint() "+(data[i]));

     // g.drawline(...);
    }
 }
 }

Edit:

Array Data is entered from MyPanel.class

import javax.swing.JPanel;

public class MyPanel extends JPanel {

    private MyPlotter plotter;

    public MyPanel(){
      setSize(320,210);
      plotter = new MyPlotter(440);
      add(this.plotter,0);
    }

    public void setData(int[] data){
      plotter.setData(data);  
    }   
}

Solution

  • I think that possibly the "repaint()" method you called modifies the original array "intValue"

    The assignment you have made data = intValue; only makes "data[]" a reference of your original array so as repaint is called seems like the data is reset or the reference is lost.If you want to copy the array you can do any of the following if a & b are two arrays:

    b = Arrays.copyOf(a, a.length);
    

    0r

    b = new int[a.length];
    System.arraycopy(a, 0, b, 0, b.length);
    

    or

    b = (int[]) a.clone();
    

    or

    int b[] = new int[a.length];
    
            for (int i = 0; i < a.length; i++) {
                b[i] = a[i];
            }