1
對於作業分配,我需要創建一個基本顯示球的程序,用戶應該可以使用左右鍵移動它。但是,該程序不響應密鑰。我不知道錯誤在哪裏,如果有人能幫忙,我會非常感激!這是代碼:在Java中使用KeyListener
public class GraphicsComponent extends JComponent
{
Ellipse2D.Double ball = new Ellipse2D.Double(200, 400, 80, 80);
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fill(ball);
g2.draw(ball);
}
}
public class BallViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame(); //creates a new JFrame called frame
frame.setSize(600,600); //invokes the method setSize on the implicit parameter frame
frame.setTitle("Move this Ball"); //sets the title of the fram
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final GraphicsComponent g = new GraphicsComponent(); //creates a new GraphicsComponent called g, is final so that the inner class can access it
frame.add(g);//adds component g to the frame
frame.setVisible(true); //sets the visibility of the frame
class PressListener implements KeyListener //creates an inner class that implements MouseListener interface
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
System.out.println("Right key pressed");
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
PressListener listener = new PressListener();
g.addKeyListener(listener);
}
}