package Project01;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.*;
public class Code01 extends Jframe{
public static void main(String[] args) {
new Code01();
}
public Code01(){
this.setBounds(100, 100,500,500);
MyJpanel jpanel=new MyJpanel(); //创建Jpanel对象
this.add(jpanel); //把Jpanel 添加到主窗体
new Thread(jpanel).start(); //开启线程
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
}
class MyJpanel extends JPanel implements Runnable{ //继承JPanel类,并实现Runnable(线程)接口
int sum=0,CirX=0,CirY=50,LineX1=150,LineX2=LineX1+200; //控制线和球的坐标,得分数值
int look=1; //来回选择
boolean temp=false;
JLabel label=new JLabel("得分:"+sum); //界面显示得分
JLabel Score=new JLabel(); //游戏结束显示得分
JDialog Tips=new JDialog(); //游戏结束d窗
JButton Exitbut=new JButton("确定并退出"); //退出游戏按钮
public void paint(Graphics g) { //重写paint类
// TODO Auto-generated method stub
super.paint(g);
g.setFont(getFont());
g.fillOval(CirX,CirY,40,40);
g.drawLine(LineX1,400,LineX2,400);
}
public void run() { //重写run类
// TODO Auto-generated method stub
while(true) {
switch(look) {
case 1:if(CirY+40!=400||!(CirX+40>=LineX1&&CirX+40<=LineX2)){CirY++;CirX++;} //控制球往右
if(CirY+40==400&&CirX+40>=LineX1&&CirX+40<=LineX2){sum+=1;label.setText("得分:"+sum);temp=true;}
if(temp){CirY-=2; if(CirX+40==490){look=2;temp=false;}}break;
case 2:if(CirY+40!=400||!(CirX+40>=LineX1&&CirX+40<=LineX2)){CirY++;CirX--;} //控制球往左
if(CirY+40==400&&CirX+40>=LineX1&&CirX+40<=LineX2){sum+=1;label.setText("得分:"+sum);temp=true;}
if(temp) {CirY-=2; if(CirX==0){look=1;temp=false;}}break;
}
if(CirY+40==500) {
Score.setText("你的得分为:"+sum);
Tips.setBounds(200,200, 300, 100);
Tips.setLayout(new FlowLayout());
Tips.add(Score);Tips.add(Exitbut);Tips.setVisible(true);
Exitbut.addMouseListener(new MouseAdapter() { //游戏退出按钮监听器
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
System.exit(0);
}
});
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint(); //刷新面板
}
}
public MyJpanel() { //面板初始化设置
this.setSize(500,500);
this.setBackground(Color .white);
this.setLayout(null );
label.setBounds(420, 20, 60, 40);
this.add(label);
this.addMouseMotionListener(new MouseMotionAdapter() { //移动线的监听器
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
LineX1=e.getX();
LineX2=LineX1+200;
}
});
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)