我试图让图像从左向右移动。我认为在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图形的初学者......
答案 0 :(得分:4)
paint
,请使用paintComponent
super.paintComponent
,否则您将遭受许多绘画工件和阴影javax.swing.Timer
代替Thread
。在事件调度线程中触发更新,降低线程污染的风险racePos = 0;
并在其他位置初始化它。看看:
了解更多详情
答案 1 :(得分:1)
我首先从绘图中删除racePos = 0
并在声明或构造函数中初始化,因为repaint()
调用paint()
方法,不断将racePos
设置为零。< / p>
尝试将y
设置为零以外的其他内容,因为您的图像可能会从屏幕上渲染出来。 JFrame
轴从左上角开始,而不是从左下角开始。