栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中聆听按键时移动图像。

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中聆听按键时移动图像。

你可以使用Swing计时器为图像设置动画:

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TimerAnimation extends JLabel implements ActionListener{    int deltaX = 2;    int deltaY = 3;    int directionX = 1;    int directionY = 1;    public TimerAnimation(        int startX, int startY,        int deltaX, int deltaY,        int directionX, int directionY,        int delay)    {        this.deltaX = deltaX;        this.deltaY = deltaY;        this.directionX = directionX;        this.directionY = directionY;        setIcon( new ImageIcon("dukewavered.gif") );//      setIcon( new ImageIcon("copy16.gif") );        setSize( getPreferredSize() );        setLocation(startX, startY);        new javax.swing.Timer(delay, this).start();    }    public void actionPerformed(ActionEvent e)    {        Container parent = getParent();        //  Determine next X position        int nextX = getLocation().x + (deltaX * directionX);        if (nextX < 0)        { nextX = 0; directionX *= -1;        }        if ( nextX + getSize().width > parent.getSize().width)        { nextX = parent.getSize().width - getSize().width; directionX *= -1;        }        //  Determine next Y position        int nextY = getLocation().y + (deltaY * directionY);        if (nextY < 0)        { nextY = 0; directionY *= -1;        }        if ( nextY + getSize().height > parent.getSize().height)        { nextY = parent.getSize().height - getSize().height; directionY *= -1;        }        //  Move the label        setLocation(nextX, nextY);    }    public static void main(String[] args)    {        JPanel panel = new JPanel();        Jframe frame = new Jframe();        frame.setContentPane(panel);        frame.setDefaultCloseOperation( Jframe.EXIT_ON_CLOSE );        frame.getContentPane().setLayout(null);//      frame.getContentPane().add( new TimerAnimation(10, 10, 2, 3, 1, 1, 10) );        frame.getContentPane().add( new TimerAnimation(300, 100, 3, 2, -1, 1, 20) );//      frame.getContentPane().add( new TimerAnimation(0, 000, 5, 0, 1, 1, 20) );        frame.getContentPane().add( new TimerAnimation(0, 200, 5, 0, 1, 1, 80) );        frame.setSize(400, 400);        frame.setLocationRelativeTo( null );        frame.setVisible(true);//      frame.getContentPane().add( new TimerAnimation(10, 10, 2, 3, 1, 1, 10) );//      frame.getContentPane().add( new TimerAnimation(10, 10, 3, 0, 1, 1, 10) );    }}

你可以将KeyListener添加到面板,它将独立于图像动画进行操作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/431860.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号