java 如何在Java中使图像从左向右移动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15443533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an image move from left to right in Java
提问by Hii
so far i have created the class below, however, now i would like to insert a code to make the image slide from left to right and right to left. I would normally use the Sliding platform however it doesn't work when i try to implement it. I am still a beginner in java so i am grateful for your help.
到目前为止,我已经创建了下面的类,但是,现在我想插入一个代码来使图像从左到右和从右到左滑动。我通常会使用滑动平台,但是当我尝试实现它时它不起作用。我仍然是 Java 的初学者,所以我很感激你的帮助。
This is the code of my Java Class:
这是我的 Java 类的代码:
package game;
import city.soi.platform.*;
public class Enemy extends Body implements CollisionListener{
private Game game ;
public Enemy(Game g){
super(g.getWorld(), new PolygonShape(-27.0f,25.0f, -27.0f,-24.0f, 25.0f,-24.0f, 26.0f,25.0f, -27.0f,25.0f));
setImage(new BodyImage("images/enemy.png"));
g.getWorld().addCollisionListener(this);
game = g;
}
public void collide(CollisionEvent e) {
if (e.getOtherBody() == game.getPlayer()){
game.getPlayer().subtractFromScore(75);
System.out.println("You have just lossed 75 Points! Current Score = " + game.getPlayer().getScore());
this.destroy();
}
}
}
Just to be clear i would like everyone i include this class onto a platform it moves from left to right.
为了清楚起见,我希望每个人都将这个课程包含在一个从左向右移动的平台上。
Many Thanks,
非常感谢,
Moe
萌
回答by MadProgrammer
This will depend a lot on what you individual requirements, but the basic concepts will remain the same.
这在很大程度上取决于您的个人要求,但基本概念将保持不变。
Any type of animation in Swing must be executed in such away that it does not block the Event Dispatching Thread. Any blocking action on the EDT will prevent any repaint request (amongst other things) from been processed.
Swing 中的任何类型的动画都必须以不阻塞事件调度线程的方式执行。EDT 上的任何阻塞操作都将阻止处理任何重绘请求(除其他外)。
This simple example uses a javax.swing.Timer
that ticks every 40 milliseconds or so (about 25 fps) and updates the position of a small "ball"
这个简单的例子使用javax.swing.Timer
每 40 毫秒左右(大约 25 fps)滴答一次并更新一个小“球”的位置
More complex iterations would require a dedicated Thread
. This makes the whole process far more complex as
更复杂的迭代需要专门的Thread
. 这使得整个过程变得更加复杂,因为
- You should never update/create/modify/change any UI component (or property that the UI may require to perform painting) from any thread other then the EDT
- You don't control the paint process. This means a repaint may occur at anytime and if you are modifying any property/object that the paint process requires to render the state of the game, it could cause inconsistencies.
- 您永远不应该从 EDT 以外的任何线程更新/创建/修改/更改任何 UI 组件(或 UI 可能需要执行绘制的属性)
- 您无法控制油漆过程。这意味着重绘可能随时发生,如果您正在修改绘制过程渲染游戏状态所需的任何属性/对象,则可能会导致不一致。
.
.
public class SimpleBouncyBall {
public static void main(String[] args) {
new SimpleBouncyBall();
}
public SimpleBouncyBall() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CourtPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CourtPane extends JPanel {
private Ball ball;
private int speed = 5;
public CourtPane() {
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Rectangle bounds = new Rectangle(new Point(0, 0), getSize());
if (ball == null) {
ball = new Ball(bounds);
}
speed = ball.move(speed, bounds);
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (ball != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point p = ball.getPoint();
g2d.translate(p.x, p.y);
ball.paint(g2d);
g2d.dispose();
}
}
}
public class Ball {
private Point p;
private int radius = 12;
public Ball(Rectangle bounds) {
p = new Point();
p.x = 0;
p.y = bounds.y + (bounds.height - radius) / 2;
}
public Point getPoint() {
return p;
}
public int move(int speed, Rectangle bounds) {
p.x += speed;
if (p.x + radius >= (bounds.x + bounds.width)) {
speed *= -1;
p.x = ((bounds.x + bounds.width) - radius) + speed;
} else if (p.x <= bounds.x) {
speed *= -1;
p.x = bounds.x + speed;
}
p.y = bounds.y + (bounds.height - radius) / 2;
return speed;
}
public void paint(Graphics2D g) {
g.setColor(Color.RED);
g.fillOval(0, 0, radius, radius);
}
}
}