第一次用swing做一个可视化程序,写第一篇随笔,有写的不好的地方请多多见谅。上个星期三在网上看到一个画爱心的软件,就想着自己用java也实现一个程序,画爱心用到的数学函数知识在网上百度的,不是本人原创的。网上也有画爱心的教程,不过那些教程只能在编译器里面运行,无法把文件导出来,导出来会出现图片资源找不到的问题,只是因为资源的使用的路径有问题,被这个问题困扰了好久,在网上找到了一种方法,把图片放到src目录下,使用类的相对路径(就是以类为基准找资源的位置)。至于画爱心主要是不断重写JPanel里面的paint方法。

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;//图片的位置,如果在src目录下,直接输入图片的位置 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 {
//通过相对路径获取图片的位置 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); }}
上面只是画一朵花的代码,要花一个完整的爱心,我是通过线程里面的循环调用这个方法实现的。
public void run() { while(love.getTheta()< 2*Math.PI){ love.repaint();//容器的重画 love.revalidate(); try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } frame.getContentPane().add(love); love.setTheta(0.33);//花的数量 } frame.getContentPane().remove(love); }