Java中小球碰撞并使用按鈕控制數(shù)量實例代碼
剛開始實訓(xùn)第三天,要求java做一個小球碰撞的小游戲,啥也不會的我,決定寫寫啥。
先根據(jù)程序要求寫了一個窗口
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();
}
}
}
}
開了倆個線程,一個數(shù)量大了有點卡
這樣運行就ok啦

另外有個拓展要求
使用鼠標控制增加球的數(shù)量
光增加怎么行呢,當(dāng)然也得來一個減少
那就再init函數(shù)里加入
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一定要加在按鈕的后面
不然是看不見畫布的
再寫倆個監(jiān)聽就行了
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方便畫布那邊檢測增減
畫布那邊簡簡單單加個設(shè)置num的函數(shù)就行
public void addnum(int i) {
if(i==0)num++;
else num--;
}
呼,完成了,就是按鈕不時地會閃現(xiàn)出來有點煩,
還有球減到0畫布可就沒了
總結(jié)
到此這篇關(guān)于Java中小球碰撞并使用按鈕控制數(shù)量的文章就介紹到這了,更多相關(guān)Java小球碰撞并控制數(shù)量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決分頁插件pagehelper在SpringBoot不起作用的問題
這篇文章主要介紹了解決分頁插件pagehelper在SpringBoot不起作用的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
spring項目自定義全局響應(yīng)處理器統(tǒng)一處理響應(yīng)結(jié)果的實現(xiàn)步驟
本文詳細描述了如何通過@ControllerAdvice和ResponseBodyAdvice在SpringMVC項目中創(chuàng)建自定義響應(yīng)處理器,以及如何使用Wrapper類包裝和標準化返回結(jié)果,感興趣的朋友跟隨小編一起看看吧2025-01-01

