How does one properly handle keypresses and repainting of a JComponent in the context of moving a ball around a screen?

前端 未结 3 1343
执笔经年
执笔经年 2020-12-11 23:28

I thought I would try and write a program that would paint a ball, and when the arrow keys are pressed, would move the ball around the screen in the direction pressed. First

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 23:44

    You can use the KeyboardFocusManager to listen for keystrokes of the arrow keys and update the position of the ball. Here is the reworked code:

    class BallFrame extends JFrame {
        private static final int DEFAULT_WIDTH = 500;
        private static final int DEFAULT_HEIGHT = 500;
        final BallComponent ball = new BallComponent();
    
        public BallFrame() {
            super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            super.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
            super.setResizable(false);
            super.add(ball);
            super.setVisible(true);
    
            KeyboardFocusManager.getCurrentKeyboardFocusManager()
                    .addKeyEventDispatcher(new KeyEventDispatcher() {
                        @Override
                        public boolean dispatchKeyEvent(KeyEvent e) {
                            if (e.getKeyCode() == KeyEvent.VK_UP)
                                ball.move(0, -10);
                            if (e.getKeyCode() == KeyEvent.VK_RIGHT)
                                ball.move(10, 0);
                            if (e.getKeyCode() == KeyEvent.VK_LEFT)
                                ball.move(-10, 0);
                            if (e.getKeyCode() == KeyEvent.VK_DOWN)
                                ball.move(0, 10);
                            return false;
                        }
                    });
    
        }
    }
    

    And for BallComponent class:

    static class BallComponent extends JComponent {
        private double x = 225;
        private double y = 225;
        private Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, 50, 50);
    
        public void move(int dX, int dY) {
            x += dX;
            y += dY;
            ellipse = new Ellipse2D.Double(x, y, 50, 50);
            repaint();
        }
    
        public void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.fill(ellipse);
        }
    }
    

提交回复
热议问题