/** * File: FFTGraph.java * Author: Brian Borowski * Date created: October 2000 * Date last modified: June 30, 2011 */ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JPanel; public class FFTGraph extends JPanel implements ComponentListener { private static final long serialVersionUID = 1L; private int[] xi, yi, yffti; private double[] x, y, yfft; private double xMin, xMax, yMin, yMax; private int width, height; private boolean overlay, showFFT, showNormal; public FFTGraph() { addComponentListener(this); } public Dimension getPreferredSize() { return new Dimension(350, 250); } private void findMinAndMax() { yMin = yMax = y[0]; xMin = x[0]; xMax = x[x.length - 1]; for (int i = 1; i < y.length; ++i) { if (y[i] < yMin) yMin = y[i]; if (yfft[i] < yMin) yMin = yfft[i]; if (y[i] > yMax) yMax = y[i]; if (yfft[i] > yMax) yMax = yfft[i]; } yMin = yMin - 0.1 * Math.abs(yMin); yMax = yMax + 0.1 * Math.abs(yMax); } public void plot(final double x[], final double y[], final double yfft[], final boolean overlay, final boolean showFFT, final boolean showNormal) { if (x == null || y == null || yfft == null) return; this.x = x; this.y = y; this.yfft = yfft; this.overlay = overlay; this.showFFT = showFFT; this.showNormal = showNormal; xi = new int[x.length]; yi = new int[y.length]; yffti = new int[yfft.length]; findMinAndMax(); fitToScreen(); repaint(); } public void componentResized(final ComponentEvent e) { fitToScreen(); } public void componentMoved(final ComponentEvent e) { } public void componentHidden(final ComponentEvent e) { } public void componentShown(final ComponentEvent e) { } private void fitToScreen() { if (x != null && y != null) { width = this.getSize().width; height = this.getSize().height; for (int i = 0; i < y.length; ++i) { xi[i] = changeXCoords(x[i]); if (!overlay) { yi[i] = (changeYCoords(y[i]) + height) / 2; yffti[i] = changeYCoords(yfft[i]) / 2; } else { yi[i] = changeYCoords(y[i]); yffti[i] = changeYCoords(yfft[i]); } } } } private int changeXCoords(final double x) { return (int)Math.round((width / (xMax - xMin)) * (x - xMax) + width - 1); } private int changeYCoords(final double y) { return (int)Math.round((height / (yMin - yMax)) * (y - yMin) + height - 1); } protected void paintComponent(final Graphics g) { g.setColor(Color.black); g.fillRect(0, 0, this.getSize().width, this.getSize().height); g.setColor(Color.darkGray); for (int i = 0; i < 8; i++) { final int x = i * width / 8; g.drawLine(x, 0, x, height); } if (xi != null) { if (!overlay) { final int y = height / 2; g.setColor(Color.darkGray); g.drawLine(0, y, width, y); } if (showNormal) { g.setColor(Color.white); g.drawPolyline(xi, yi, xi.length); } if (showFFT) { g.setColor(Color.green); g.drawPolyline(xi, yffti, xi.length); } } } }