1.9鼠标控制小球

1.9鼠标控制小球_第1张图片
1.9鼠标控制小球_第2张图片
1.9鼠标控制小球_第3张图片

import java.awt.*;

import javax.swing.*;

import java.awt.event.MouseEvent;

import java.awt.event.MouseMotionListener;

public class MyBall{

public static void main(String[] args){

JFrame w = new JFrame();

w.setSize(300, 400);

MyPanel mp = new MyPanel();

w.add(mp);

w.addMouseMotionListener(mp);

mp.addMouseMotionListener(mp);

w.setVisible(true);

}

}

class MyPanel extends JPanel implements MouseMotionListener{

int x = 30;

int y = 30;

public void paint(Graphics g){

super.paint(g);

g.fillOval(x, y, 20, 20);

}

@Override

public void mouseDragged(MouseEvent arg0){

//鼠标拖动

x = arg0.getX();

y = arg0.getY();

repaint();

}

@Override

public void mouseMoved(MouseEvent arg0){

}

}


以下是小球自由下落。


1.9鼠标控制小球_第4张图片
1.9鼠标控制小球_第5张图片

import java.awt.*;

import javax.swing.*;

public class MyBall{

public static void main(String[] args){

JFrame w = new JFrame();

w.setSize(300, 400);

MyPanel mp = new MyPanel();

w.add(mp);

Thread t = new Thread(mp);

t.start();

w.setVisible(true);

}

}

class MyPanel extends JPanel implements Runnable{

int x = 30;

int y = 30;

public void paint(Graphics g){

super.paint(g);

g.fillOval(x, y, 20, 20);

}

public void run(){

while(true){

y++;

if(y>400){

y = 0;

}

try{

Thread.sleep(20);

}catch(Exception e){

}

repaint();

}

}

}

你可能感兴趣的:(1.9鼠标控制小球)