让一个小球动起来,让后再跳起来。
先上老师代码,各种 注释很详细。
再上我的代码,实现跳动 效果。
package day04;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TeacherBall {
public static void main(String [] args){
//1.创建窗体对象
JFrame frame = new JFrame("MyBall");
//2.设置窗体的大小
frame.setSize(400,500);
//设置窗体居中显示
//frame.setLocation(x, y)
//frame.setBounds(100, 100, 400, 500);
frame.setLocationRelativeTo(null);
//3.默认的关闭操作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建MyPanel对象
TePanel panel = new TePanel();
//把panel添加到frame中
frame.add(panel);
//4.显示窗体
frame.setVisible(true);
panel.run(); //对象调用方法
}
}
class TePanel extends JPanel{
//定义小球的x,y坐标
int x = 30 ;
int y = 30 ;
//重写父类(JPanel)中的paint方法
public void paint(Graphics g){
//
super.paint(g);
//画小球
g.fillOval(x, y, 30, 30);
}
public void run(){
while(true){
//一直改变y坐标
y++;
if(y>430){
y=0;
}
//一直去调用paint 方法
//重绘
repaint();//通知系统,赶快去调用paint 方法
//休息一会
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Unhandled exception type InterruptedException
}
}
}
//24
package day04;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyBall {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("MyBall");
frame.setSize(400, 500);
// 设置窗体居中 显示
// 不相对于任何组件
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MyPanel panel = new MyPanel();
frame.add(panel);
panel.run();
}
}
class MyPanel extends JPanel {
int x = 30;
int y = 30;
int z = 0;
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillOval(x, y, 30, 30);
}
public void run() {
while (true) {
if (z == 0) {
y++;
if (y == 435) {
z = y;
}
} else if (z == 435) {
y--;
if (y == 0) {
z = y;
}
}
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}