0
請注意,我對所有這些編程都很陌生。現在我有一個框架,它增加了一個面板。我相信在面板上使用了paintcomponent方法,但現在當我嘗試使用keylisteners時,我需要移動我在面板上繪製的圖像。我目前不知道如何重畫它。試圖重新繪製一個jpanel
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings
("serial")
public class Game extends JPanel implements KeyListener
{
Car fo = new Car();
draw a=new draw();
public Game()
{
JFrame frame2=new JFrame("JASA1 Racing");
frame2.add(new draw());
frame2.setSize(500,600);//set frame size
frame2.setVisible(true);//made frame visible
frame2.setResizable(false);
frame2.addKeyListener(this);
frame2.setFocusable(true);
}
public class draw extends JPanel
{
private static final long serialVersionUID = 1L;
public void redraw()
{
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon ic2=new ImageIcon("C:\\Users\\Shawn\\track.jpg");
Image img=ic2.getImage();
g.drawImage(img, 0, 0,null);
g.drawImage(fo.getcar(),fo.getX(),fo.getY(),null);
System.out.println(fo.getX() + " " + fo.getY());
}
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT)
{
fo.move(-50, 0);
System.out.print(fo.getX());
a.repaint();
}
else if(key == KeyEvent.VK_RIGHT)
{
fo.move(50, 0);
System.out.print(fo.getX());
a.redraw();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
OMG它的工作重點的問題。謝謝你太多了! – user3180075