0

I was wondering if it is possible to create a sine-grating like this in a JPanel using only Java2D.

I am not very adept with Swing and Java2D jet, so there might be simple things I am missing. If it is in fact not possible to do this could someone please provide me with an easy tutorial how to use OpenGL with JOGL inside a JPanel? I know Java2D and JOGL work together quite nicely but I really dont know how to initialize things to get a OpenGL graphic to show up in my normal GUI.

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • You might experiment with `java.awt.LinearGradientPaint` or this [example](http://stackoverflow.com/q/7544559/230513). – trashgod Jul 07 '14 at 21:35
  • trashgod's suggestion should be enough if you want to stick with Java2D. If you're afraid of learning how to use JOGL/OpenGL, you can look at Jzy3D even for 2D stuffs, it uses JOGL under the hood but it's easier to use. What do you mean by "normal GUI"? – gouessej Jul 08 '14 at 10:31
  • Thank you both for your replies! java.awt.LinearGradientPaint was in fact exactly what i was looking for! – BjoernBeyer Jul 15 '14 at 20:26

1 Answers1

0

The question was essentially answered by trashgod. Using LinearGradientPaint one can create a real sine-wave grating by using a linear grading with many samplePoints. An example function that creates a sine-wave grating is below.

Thanks again for your help!

public LinearGradientPaint getSineWaveGrating(int numberCycles, int samplePoints, Point2D startP, Point2D endP, Color color) {   
  float[] fractions = new float[samplePoints+1];
  Color[] colors    = new Color[samplePoints+1];

  for(int i=0;i<=samplePoints;i++) {
    fractions[i]        = i*(1/(float)samplePoints); 
    double cosArg       = Math.PI+((i*numberCycles*2*Math.PI)/samplePoints);
    double rectifiedCos = (Math.cos(cosArg)+1)/2;
    colors[i]           = new Color(color.getRed(),color.getGreen(),color.getBlue(),(int)(255*rectifiedCos));
  }

  return new LinearGradientPaint(startP, endP, fractions, colors);
}