In this project we are going to make a GUI component with Java that draws integer values so we can see lines rather than plain numbers. The class is called Oscilloscope and it extends the javax.swing.JPanel class, so we can use the Graphics instance in the paintComponent() method.
The data are stored in a LinkedList (java.util) with the use of the addVal(int x) method. This kind of list is used because it implements the Queue interface. When the data becomes too many to present to the panel, the records on the tail are dropped so the new ones can be added in the head. This creates a sense of scrolling leftwards
import java.awt.Graphics; import javax.swing.JPanel; import java.util.LinkedList; public class Osciloscope extends JPanel{ public LinkedList<Integer> list = new LinkedList<Integer>(); public Osciloscope(){ super(); } public void addVal(int x){ list.offer(x); if (list.size()>getWidth()) list.poll(); } public void paintComponent(Graphics g){ super.paintComponent(g); for (int i=1;i<list.size();i++){ double val1 = list.get(i)/1024.0*getHeight(); double val2 = list.get(i-1)/1024.0*getHeight(); val1 = getHeight() - val1; val2 = getHeight() - val2; g.drawLine(i, (int) val1, i,(int) val2); } } }
The core of the program is in the for loop inside the paintComponent() method. We iterate all the records of the LinkedList, and draw a line connecting the current point and the previous (notice how se start from i=1 and not i=0). Also the code uses the formula list.get(i)/1024.0*getHeight() to scale the values taken (0 to 1024) to the current size of the JPanel. Lastly of course we invert the value ( val = getHeight() - val ) so the panel corresponds to the Cartesian coordinate system where the zeroes are bottom left ( not top left where the JPanel's are )
This project works perfectly with the SerialSocket class developed here where the socket reads and parses integer values from the serial connection (probably from the analog inputs of an Arduino) and projεcts the data to the screen.
No comments:
Post a Comment