本文主要是介绍让蒲公英飘动起来,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
晚上回到宿舍,突然想起,我可以把昨天晚上的代码修改一下,来让我的蒲公英达到飘动的效果,然后就把代码乱修改了一番,代码如下,但是飘动的效果得在运行的时候才能看出来,具体代码如下:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;import javax.swing.JFrame;
import javax.swing.JPanel;/*** 画出一颗动态的蒲公英。。。。(画出蒲公英的改进版,使得蒲公英可以飘动)* @author LONG**/
public class TheTree extends JFrame {private static final long serialVersionUID = 1L;private Dimension di = null;private Graphics2D gr = null;private int x,y; //蒲公英初始飘动的点private JPanel jp = null; //将面板声明为全局变量private int count = 0; //用来记录次数/*** 程序主入口* @param args*/public static void main(String[] args){TheTree tt = new TheTree();tt.showFrame();}/*** 展示窗体,将窗体显示出来*/public void showFrame(){this.setTitle("The Tree");Toolkit tl = Toolkit.getDefaultToolkit();di = tl.getScreenSize();this.setSize(di.width,di.height);this.setDefaultCloseOperation(3);jp = new JPanel();jp.setPreferredSize(new Dimension(di.width,di.height));x = di.width; //初始化坐标值,使其最大y = di.height; //初始化坐标值,使其最大this.add(jp);this.setResizable(false);jp.setBackground(Color.BLACK);this.setVisible(true);gr = (Graphics2D) jp.getGraphics();//给界面添加监听器,判断执行次数jp.addMouseListener(new MouseAdapter(){public void mouseReleased(MouseEvent e){draw(e);}}); }/*** 初始进行选择,来判断是初次绘画还是改变后* @param e 传入点击事件*/public void draw(MouseEvent e){while(y > 0){if(count == 0){x = e.getX(); //自己选择蒲公英生长的位置y = e.getY();}else{y -= 5; //非初次的话,那么进行改变位置,传入参数x += 6;} init(x,y); //执行下面的函数}}//用来初始化蒲公英的位置,达到飘动的效果public void init(int xx,int yy){BasicStroke bs = new BasicStroke(4);gr.setStroke(bs);gr.setColor(Color.GREEN);gr.drawLine(xx, yy, xx, yy - 400); //用来先画出蒲公英的主干doSomething(xx,yy - 400,150);}/***那我们来画蒲公英吧* * @param x1 起始点x坐标* @param y1 起始点y坐标* @param h 长度h*/public void doSomething(int x1, int y1, int h){//使循环将所有的蒲公英分支画出来for(int i = 0; i < 90; i++){double angle = i * 2 * Math.PI/90; //得到等分的九十个角int x2 = x1 + (int)(Math.sin(angle) * h);int y2 = y1 - (int)(Math.cos(angle) * h);BasicStroke bs_next = new BasicStroke();gr.setStroke(bs_next);gr.setColor(Color.gray);gr.drawLine(x1, y1, x2, y2);gr.setColor(Color.WHITE);gr.fillOval(x2 - 1, y2 - 1, 5, 5);}try {Thread.sleep(120);} catch (InterruptedException e) {e.printStackTrace();}//再次将蒲公英画黑,重复上面的画的动作,只不过是将所有的颜色都改为黑色的,已达到飘动的效果BasicStroke bs = new BasicStroke(4);gr.setStroke(bs);gr.setColor(Color.BLACK);gr.drawLine(x1, y1 + 400, x1, y1); for(int i = 0; i < 90; i++){double angle = i * 2 * Math.PI/90; int x2 = x1 + (int)(Math.sin(angle) * h);int y2 = y1 - (int)(Math.cos(angle) * h);BasicStroke bs_next = new BasicStroke();gr.setStroke(bs_next);gr.setColor(Color.BLACK);gr.drawLine(x1, y1, x2, y2);gr.setColor(Color.BLACK);gr.fillOval(x2 - 1, y2 - 1, 5, 5);}count++;}
}
这篇关于让蒲公英飘动起来的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!