java - 如何在 Java 中跨 JPanel 移动图像?

标签 java swing animation

我试图让图像从左向右移动。我认为增加 run 方法中的 x 位置可以实现此目的,但图像只是在面板上移动。我在这里缺少什么概念?

下面是我的代码:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.lang.Math;

public class Races extends JFrame
 {
//Global variables
Icon imgPacman;
JLabel lblPacman;
JSeparator finishLine; 
RaceThread pacmanRace;
Thread tRace;

 int screenWidth;
 int screenHeight;

 public Races()
 {
    initialize();
 }

 public void initialize()
 {
  //Initial frame setup
  this.setTitle("Races");
  this.setLayout(new GridLayout(0, 1));

  //Image          
  imgPacman = new ImageIcon("races.gif");
  screenWidth = imgPacman.getIconWidth() * 20;
  screenHeight = (int) (imgPacman.getIconHeight() * 1.8);

  pacmanRace = new RaceThread(imgPacman);

  //Thread
  tRace = new Thread(pacmanRace);
  tRace.start();

  //Final frame setup
  this.add(pacmanRace);
  this.setSize(screenWidth, screenHeight);
  this.setLocationRelativeTo(null);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
 }

 protected class RaceThread extends JPanel implements Runnable
 {       
  Icon aIcon;
  int racePos;

  public RaceThread(Icon _aIcon)
  {
     aIcon = _aIcon;
     this.setBorder(BorderFactory.createLineBorder(Color.orange));
  }

  public void run()
  {
     int waitTime = (int) (Math.random() * 100);
     while(true)
     {
        repaint();
        racePos++;         
     }     
  }

  public void paint(Graphics g)
  {
     racePos = 0;
     aIcon.paintIcon(this, g, racePos, 0);
  }            
  }//end of inner class


 public static void main(String[] args)
 {
  new Races();
 }

}//end of class

请记住,我是 Java 图形初学者...

最佳答案

  • 不要使用paint,使用paintComponent
  • 在进行任何自定义绘画之前调用 super.paintComponent,否则您将遭受许多绘画伪像和阴影
  • 考虑使用javax.swing.Timer而不是Thread。更新在事件调度线程内触发,降低了线程污染的风险
  • Paint 方法用于绘画,不要从中更新组件的状态。例如,从您的绘制方法中删除 racePos = 0; 并在其他位置对其进行初始化。

看一下:

了解更多详情

关于java - 如何在 Java 中跨 JPanel 移动图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23329882/

相关文章:

java - 如何获取应用程序退出前读取的数据库表的最后一行行号

java - 将图标放入 JTable 单元格会更改其背面颜色

javascript - 添加项目的 meteor 动画

Java servlet,从文件读取,数组越界

java - 如何创建 Battleship 战舰游戏算法

java - 我收到错误 : Invocation of init method failed; nested exception is org. hibernate.MappingException: Repeated column in mapping for entity

animation - JavaFX Animation 类的 'rate' 属性如何表现?

Java 拆分在使用 | 时停在空白处作为分隔符

java - JTable 单元格中功能齐全的 JTree 不起作用

ios - UIViewControllerAnimatedTransitioning : screen keeps getting black under custom view