1
當它切換圖標的圖像閃爍時形成某種原因。當我嘗試創建對象時,我還遇到了這個問題,然後嘗試通過將x和y作爲參數傳遞給對象來移動它們。任何幫助都會很棒。Java ImageIcon動畫閃爍
public class Main extends JFrame implements ActionListener, KeyListener{
static Main main;
Render render;
Timer timer;
static int x,y,count;
ImageIcon player1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player1.png");
ImageIcon player2 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player2.png");
Main(){
render = new Render();
timer = new Timer(100,this);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(this);
add(render);
timer.start();
}
public void render(Graphics g){
count += 1;
if(count < 20){
player1.paintIcon(this, g, x, y);
}
if(count > 20){
player2.paintIcon(this, g, x, y);
}
if(count > 40){
count = 0;
}
}
public static void main(String [] args){
main = new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(count);
render.repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int id = e.getKeyCode();
int speed = 4;
if(id == KeyEvent.VK_UP){
y -= speed;
}
if(id == KeyEvent.VK_DOWN){
y += speed;
}
if(id == KeyEvent.VK_LEFT){
x -= speed;
}
if(id == KeyEvent.VK_RIGHT){
x += speed;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
渲染類。
public class Render extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
Main.main.render((Graphics)g);
}
}
想通了。我不得不將「if(count> 20)」更改爲「if(count> = 20)」。以及將「count + = 1」移動到ActionListener –