展开全部
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CelMove extends JFrame {
e68a8462616964757a686964616f31333337616538private static final long serialVersionUID = 3171295325956127838L;
CelJPanel cjp;
static int width = 500, height = 380;
public CelMove() {
// 设置方块的初始位置
cjp = new CelJPanel(width / 2, height / 2);
// 设置方块的背景颜色
cjp.setBackground(Color.YELLOW);
// 设置绘制方块的面板的大小
cjp.setSize(width, height);
// 添加鼠标事件 让方块跟着鼠标移动
this.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();//得到鼠标点击的位置
cjp.lx = p.x;//设置当方块x坐标=点击的x作弊
if (cjp.lx > width - 28) {// 28是空出来的一个左右边框大小.为了不让方块移动出了界面
cjp.lx = width - 28;// 如果超过边界.就设置方块的x ,回到边框内
}
if (cjp.lx
cjp.lx = 0;
}
cjp.ly = p.y;
if (cjp.ly > height - 50) {// 50是空出来的一个上下边框大小.为了不让方块移动出了界面
cjp.ly = height - 50;
}
if (cjp.ly
cjp.ly = 0;
}
// lx,ly坐标设置完成,才执行repaint()重绘
cjp.repaint();
}
// 当拖动鼠标的时候..
@Override
public void mouseDragged(MouseEvent e) {
}
});
// 添加一个键盘事件
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int speed = 10;
// S 和 下箭头 可以向下移动
if (e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_DOWN) {
// 这里没有写是否出界的代码.你可以先判断移动后是否会超过边框
cjp.ly = cjp.ly + speed;
cjp.repaint();
}
// W 和 上箭头 可以向上移动
if (e.getKeyCode() == KeyEvent.VK_W || e.getKeyCode() == KeyEvent.VK_UP) {
cjp.ly = cjp.ly - speed;
cjp.repaint();
}
// A 和 左箭头 可以向左移动
if (e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT) {
cjp.lx = cjp.lx - speed;
cjp.repaint();
}
// D 和 右箭头 可以向右移动
if (e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT) {
cjp.lx = cjp.lx + speed;
cjp.repaint();
}
}
});
// 设置主窗口的相关属性
this.setLayout(null);
this.add(cjp);
this.setTitle("移动方块");
this.setLocation(150, 100);
this.setSize(width, height);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new CelMove();
}
// 绘制方块的类
class CelJPanel extends JPanel {
int lx, ly;
public CelJPanel(int lx, int ly) {
super();
this.lx = lx;
this.ly = ly;
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(lx, ly, 20, 20);
}
}
}
你参考下吧,很久前写的