我试图让图像从左向右移动。我认为增加 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/