The first time with swing to do a visual program, write the first essay, there is a bad place to write a lot of forgive me. Last Wednesday on the internet to see a painting love software, think of their own Java also realize a program, painting love with the mathematical function of knowledge in the online Baidu, not my original. Online also have a love of painting tutorial, but those tutorials can only be run in the compiler, unable to export files, export will appear image resources can not find the problem, just because the use of the path of resources problems, was plagued by this problem for a long time, found on the internet a way to put pictures in the SRC directory, Use the relative path of the class (that is, where the resource is located on the class basis). As for the painting love is to constantly rewrite the jpanel inside the paint method.
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import java.io.IOException;
Import Javax.imageio.ImageIO;
Import Javax.swing.JPanel;
public class Drawlove extends jpanel{
Private Image Image1;
Private String str1;//The position of the picture, if the location of the image is directly entered in the SRC directory
Private double theta=0.00;
Private double x, y;
Private Graphics G;
Public double Gettheta () {
return theta;
}
public void Settheta (double theta) {
This.theta + = theta;
}
Public Drawlove (String str1) {
THIS.STR1=STR1;
This.setlayout (NULL);
}
public void Paintcomponent (Graphics g)
{
try {
Get the position of a picture by a relative path
Image1=imageio.read (This.getclass (). getClassLoader (). getResourceAsStream (STR1));
} catch (IOException e) {
E.printstacktrace ();
}
graphics2d g2 = (graphics2d) g;
x= 580-15* (28*math.pow (Math.sin (Theta), 3));
Y= 240-15* (20*math.cos (theta) -6*math.cos (2*theta) -3*math.cos (3*theta)-math.cos (4*theta));
G2.drawimage (Image1, (int) x, (int) y,null);
}
}
The above is just the code to draw a flower, to spend a complete love, I am through the thread inside the loop call this method to achieve.
public void Run () {
while (Love.gettheta () < 2*math.pi) {
Love.repaint ();//re-painting of containers
Love.revalidate ();
try {
Thread.Sleep (time);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Frame.getcontentpane (). Add (Love);
Love.settheta (0.33);//Number of flowers
}
Frame.getcontentpane (). Remove (Love);
}
Java Swing Drawing Love