- #1

- 39

- 0

here is the code

import javax.swing.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.awt.image.*;

import javax.imageio.*;

public class esfera extends JFrame{

double azimuth=3*Math.PI/4, inclination=Math.PI/4; //angle coordinates for the 'light source'

private BufferedImage image = new BufferedImage(800,800,BufferedImage.TYPE_INT_RGB); //the image storing the sphere drawing

public esfera(){ //initializer adding a listener to mouse motion

addMouseMotionListener(new MouseMotionAdapter(){

public void mouseDragged(MouseEvent e){

azimuth=((800-e.getX())/800.00)*Math.PI;

inclination=(e.getY()/800.00)*Math.PI;

repaint();

}

});}

public void paint(Graphics g){ //does the whole painting

g.drawImage(image,0,0,null); //paint the current image to the frame

for(int i=0;i<800;i++){ //make next image, pixel by pixel

for(int j=0;j<800;j++){

image.setRGB(i,j,color((i-400)/200.00,(400-j)/200.00));

}

}

}

public int color(double x, double y){ //this is what color each pixel should be painted in order to make the picture look like a sphere

double clr;

double z = Math.sqrt(1-(x*x+y*y));

double angle = Math.acos(Math.cos(inclination)*y+Math.sin(inclination)*(Math.sin(azimuth)*z+Math.cos(azimuth)*x));

if(x*x+y*y>1) clr=0;

else if (angle>Math.PI/2) clr=0;

else if (angle>Math.PI/4)clr=255*(2-angle/(Math.PI/4));

else{ int white =((int)(255*(1-angle/(Math.PI/4)))<<8)+((int)(255*(1-angle/(Math.PI/4)))<<16);

clr=white+255;}

return (int)clr;

}

public static void main(String[] args){ //the main method of course

esfera frame = new esfera();

frame.setSize(800,800);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

it works ok. the only problem is that when you move the mouse it takes too long to update the screen with the next picture.(so the 'light source' seems to be jumping from one place to another if you move the mouse too fast)

the question is: how can I fix this problem?

i have been reading about VolatileImage but it seems that you can't write a VolatileImage pixel by pixel, so it's not what i need.

i have also read about BufferStrategy, but i'm not sure if it could help me or not, (didn't completely understand how to use it neither)

could you help me please??? i've been trying to solve it all day...