怎么编写java程序实现图片的移动(最好有例子)

怎么编写java程序实现图片的移动(最好有例子),第1张

import java.awt.Color

import java.awt.Graphics

import java.awt.Image

import java.awt.event.KeyAdapter

import java.awt.event.KeyEvent

import javax.swing.JFrame

public class DrawTest extends JFrame {

private int x = 50

private int y = 50

private Image offScreenImage = null

@Override

public void paint(Graphics g) {

Color c = g.getColor()

g.setColor(Color.BLACK)

g.fillOval(x, y, 30, 30)

g.setColor(c)

}

public void update(Graphics g) {

if (offScreenImage == null) {

offScreenImage = this.createImage(500, 500)

}

Graphics gOffScreen = offScreenImage.getGraphics()

Color c = gOffScreen.getColor()

gOffScreen.setColor(Color.GREEN)

gOffScreen.fillRect(0, 0, 500, 500)

gOffScreen.setColor(c)

paint(gOffScreen)

g.drawImage(offScreenImage, 0, 0, null)

}

public static void main(String[] args) {

DrawTest d = new DrawTest()

}

public DrawTest() {

init()

addKeyListener(new KeyAdapter() {

public void keyPressed(final KeyEvent e) {

int code = e.getKeyCode()

switch (code) {

case KeyEvent.VK_UP:

y -= 5

break

case KeyEvent.VK_RIGHT:

x += 5

break

case KeyEvent.VK_DOWN:

y += 5

break

case KeyEvent.VK_LEFT:

x -= 5

break

}

}

})

}

public void init() {

this.setDefaultCloseOperation(this.EXIT_ON_CLOSE)

this.setBackground(Color.GREEN)

this.setResizable(false)

this.setBounds(140, 140, 500, 500)

this.setVisible(true)

MyThread mt = new MyThread()

new Thread(mt).start()

}

class MyThread implements Runnable {

public void run() {

while (true) {

repaint()

try {

Thread.sleep(100)

} catch (InterruptedException e) {

e.printStackTrace()

}

}

}

}

}

以上

这个只是实现了移动,你参考以下吧 !

public class MoveImage {

static int x,y

private static int num=0

private static Icon icon=null

public static void main(String[] args) throws Exception{

JFrame f = new JFrame()

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

f.getContentPane().setLayout(null)//这个要设置成 null

//图片

icon = new ImageIcon("d:/test.gif")//d:/test.gif本地一张图片

JLabel l = new JLabel(icon)//创建具有指定图像的 JLabel 实例。

l.setSize(icon.getIconWidth(),icon.getIconHeight())//设置面板的宽度和高度

l.setBorder(BorderFactory.createLineBorder(Color.red))//给图片加上红色外框

f.getContentPane().add(l)

f.setSize(900,700)

f.setVisible(true)

l.addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent e){

x=e.getX()

y=e.getY()

}

})

l.addMouseMotionListener(new MouseMotionListener(){

public void mouseDragged(MouseEvent e) {

JLabel l = (JLabel)e.getSource()

l.setLocation(l.getX()+e.getX()-x,l.getY()+e.getY()-y)

}

public void mouseMoved(MouseEvent e) {}

})

}

改变规制时候的X Y就行了.伪代码如下.

int x =0,y=0,

x++y++

g.drawImage( "图片信息" , x, y,锚点)

大概就这样图片就动了.你想移动到哪加个判断就行了.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12033190.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存