试图重新绘制jpanel

时间:2014-01-10 02:15:50

标签: java swing jpanel keylistener repaint

请注意,我对所有这些编程都很陌生。现在我有一个框架,它添加了一个面板。我在面板上使用paintcomponent方法我相信,但现在当我尝试使用keylisteners时,我需要移动我在面板上绘制的图像。我目前不知道如何重新绘制它。

 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)
    {
    }

}

1 个答案:

答案 0 :(得分:2)

draw a=new draw();不是您添加到框架中的内容,而是使用frame2.add(new draw());代替。

尝试使用frame2.add(a);

我还考虑使用Key Bindings,因为它可以帮助您克服与KeyListener相关的焦点问题