用键盘事件中的KeyPrssed()方法移动图像(Java)

效果图:

 代码实现:

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

//图像移动事件
public class ImageMove extends KeyAdapter {
    JFrame frame = new JFrame("通过方向键改变图像位置");
    Icon image = new ImageIcon("D:\\java项目\\src\\images\\header.png");
    JLabel lb = new JLabel(image);
    int x = 50;
    int y = 50;

    @Override
    public void keyPressed(KeyEvent e) {//键盘按下事件
        if(e.getKeyCode() == KeyEvent.VK_UP){//向上移动
            if(y > 10)
                y = y - 10;
        }
        if(e.getKeyCode() == KeyEvent.VK_DOWN){//向下移动
            if(y < 240)
                y = y + 10;
        }
        if(e.getKeyCode() == KeyEvent.VK_LEFT){//向左移动
            if(x > 10)
                x = x - 10;
        }
        if(e.getKeyCode() == KeyEvent.VK_RIGHT){//向右移动
            if(x < 240)
                x = x + 10;
        }
        lb.setBounds(x,y,150,150);//移动后的图像位置和大小
    }
    public void init(){
        frame.setLayout(null);
        lb.setBounds(x,y,150,150);//初始化图像位置和大小
        frame.add(lb);
        frame.addKeyListener(this);//为窗体添加键盘事件
        frame.setBounds(700,250,400,400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ImageMove().init();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

T何必当初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值