Java中小球碰撞并使用按钮控制数量实例代码

刚开始实训第三天,要求java做一个小球碰撞的小游戏,啥也不会的我,决定写写啥。

先根据程序要求写了一个窗口

package three.day; import java.awt.event.*;import javax.swing.*; public class Windows extends JFrame{DrowJPs jp=new DrowJPs();public void init() {this.setSize(800,500);this.setLocationRelativeTo(rootPane);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setTitle("天沫丶寒枫");this.add(jp);this.setVisible(true);}public static void main(String[] args) {Windows win=new Windows();win.init();} }

然后写一个画图

package three.day;import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel; public class DrowJPs extends JPanel implements Runnable{int[] x=new int[1000],y=new int[1000],s=new int[1000],xt=new int[1000],yt=new int[1000];int[] r=new int[1000],g=new int[1000],b=new int[1000];int num=5;public DrowJPs() {for (int i = 0; i < 1000; i++) {x[i]=(int)(Math.random()*450);y[i]=(int)(Math.random()*230);r[i]=(int)(Math.random()*256);g[i]=(int)(Math.random()*256);b[i]=(int)(Math.random()*256);xt[i]=(int)(Math.random()*4+1);yt[i]=(int)(Math.random()*4+1);s[i]=(int)(Math.random()*200+20);}Thread t=new Thread(this);Thread t1=new Thread(this);t.start();t1.start();}public void paint(Graphics gr) {super.paint(gr);setBackground(Color.pink);for (int i = 0; i < num; i++) {gr.setColor(new Color(r[i],g[i],b[i]));gr.fillOval(x[i], y[i], s[i], s[i]);}}public void run() {while(true) {for (int i = 0; i < num; i++) {if(x[i]<=0|x[i]>=(790-s[i]))xt[i]*=-1;if(y[i]<=0|y[i]>=(465-s[i]))yt[i]*=-1;x[i]+=xt[i];y[i]+=yt[i];try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}repaint();}}}}

开了俩个线程,一个数量大了有点卡

这样运行就ok啦

另外有个拓展要求

使用鼠标控制增加球的数量

光增加怎么行呢,当然也得来一个减少

那就再init函数里加入

        JButton btn = new JButton("增加一个小球");JButton btn1 = new JButton("减少一个小球");btn.setBounds(0, 0, 400, 600);btn1.setBounds(400, 0, 400, 600);this.add(btn);this.add(btn1);btn.addActionListener(new MyListener());btn1.addActionListener(new MyListener1());

注意画布jp一定要加在按钮的后面

不然是看不见画布的

再写俩个监听就行了

    class MyListener implements ActionListener{public void actionPerformed(ActionEvent e) {jp.addnum(0);}}class MyListener1 implements ActionListener{public void actionPerformed(ActionEvent e) {jp.addnum(1);}}

传01方便画布那边检测增减

画布那边简简单单加个设置num的函数就行

public void addnum(int i) {if(i==0)num++;else num--;}

呼,完成了,就是按钮不时地会闪现出来有点烦,

还有球减到0画布可就没了

总结

到此这篇关于Java中小球碰撞并使用按钮控制数量的文章就介绍到这了,更多相关Java小球碰撞并控制数量内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

人生不如意十之八-九,与其诅咒黑暗,倒不如在生命中点燃一盏灯

Java中小球碰撞并使用按钮控制数量实例代码

相关文章:

你感兴趣的文章:

标签云: