0

I have a game in which two ellipses appear on a JFrame, one controlled by the a - s - d - w keys and the other one controlled by the arrow keys. Here is my run method:

public void run() {
        while (animator != null) {
            repaint();

            player1.move(player1.direction);
            player2.move(player2.direction);
            try {  
                Thread.sleep(100);  
            } catch (InterruptedException e) {  
                break;  
            }  
        }
}

Here is my individual player classes. This is the paintComponent method of the player 1 class. (Player 1 and Player 2 are identical) The variables shape, xPos, yPos, size, and Color are all fine. (They are attached to values)

public void paintComponent(Graphics g) { 
    Graphics2D g2 = (Graphics2D)g;

    switch(Shape) {
    case 1: Ellipse2D.Double ball = new Ellipse2D.Double(xPos, yPos, size, size);         
    g2.setPaint(Color);
    g2.draw(ball);
    g2.fill(ball);
    break;

    case 2: Rectangle2D.Double rectangle = new Rectangle2D.Double(xPos, yPos, size, size);
    g2.setPaint(Color);
    g2.draw(rectangle);
    g2.fill(rectangle);
    break;
    }   
}       

I control the direction of the ellipses through the use of a class called KeyController. Here is a sample part of that program; The rest is the same (Remember that is just an excerpt):

public void keyPressed(KeyEvent e) {
    // Player 1 Left
    if(e.getKeyCode() == KeyEvent.VK_A){
        Player1.setDirection(270);
        System.out.println("A pressed");
    }

    // Player 1 Down
    if(e.getKeyCode() == KeyEvent.VK_S){
        Player1.setDirection(180);
        System.out.println("S pressed");
    }

    if(e.getKeyCode() == KeyEvent.VK_LEFT){
        Player2.setDirection(270);
        System.out.println("LEFT pressed");
    }

    if(e.getKeyCode() == KeyEvent.VK_DOWN){
        Player2.setDirection(180);
        System.out.println("DOWN pressed");
    }

The rest of the program runs fine. (It has a keyTyped and a keyPressed)

Now my question is that when I run my program, I see one ellipse and all keys can control it, both the a - s - d - w keys and the arrow keys.

If you need more code, just ask me. (I have a main method and it works fine.)

How to make Ellipse respond to controls?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Anonymous181
  • 1,863
  • 6
  • 24
  • 27
  • 3
    1) *"If you need more code, just ask me."* Not a question, so much as an observation, but for better help sooner, post an [SSCCE](http://sscce.org/). 2) Look into key bindings if using Swing. – Andrew Thompson May 01 '12 at 22:54
  • 1
    See also [`LinePanel`](http://stackoverflow.com/a/5797965/230513). – trashgod May 02 '12 at 04:47

1 Answers1

0

Here is a small example of moving a circle with keys:

public static void main ( String[] args )
{
    JFrame controls = new JFrame ();

    controls.add ( new JComponent ()
    {
        private Point location = new Point ( 250, 250 );
        private int speed = 5;

        {
            setFocusable ( true );
            requestFocusInWindow ();
            addKeyListener ( new KeyAdapter ()
            {
                public void keyPressed ( KeyEvent e )
                {
                    boolean changed = false;
                    if ( e.getKeyCode () == KeyEvent.VK_W || e.getKeyCode () == KeyEvent.VK_UP )
                    {
                        location.y -= speed;
                        changed = true;
                    }
                    else if ( e.getKeyCode () == KeyEvent.VK_A ||
                            e.getKeyCode () == KeyEvent.VK_LEFT )
                    {
                        location.x -= speed;
                        changed = true;
                    }
                    else if ( e.getKeyCode () == KeyEvent.VK_S ||
                            e.getKeyCode () == KeyEvent.VK_DOWN )
                    {
                        location.y += speed;
                        changed = true;
                    }
                    else if ( e.getKeyCode () == KeyEvent.VK_D ||
                            e.getKeyCode () == KeyEvent.VK_RIGHT )
                    {
                        location.x += speed;
                        changed = true;
                    }
                    if ( changed )
                    {
                        repaint ();
                    }
                }
            } );
        }

        protected void paintComponent ( Graphics g )
        {
            Graphics2D g2d = ( Graphics2D ) g;
            g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON );

            g2d.setPaint ( Color.BLACK );
            g2d.drawOval ( location.x - 10, location.y - 10, 20, 20 );
        }
    } );

    controls.setSize ( 500, 500 );
    controls.setLocationRelativeTo ( null );
    controls.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    controls.setVisible ( true );
}

When using simple Key listener be sure that component has focus - otherwise it won't recieve any key events at all. So you have to change focused component forcefully sometimes:

component.requestFocusInWindow ();
Mikle Garin
  • 10,083
  • 37
  • 59
  • 1
    isn't safest ans simplest to use KeyBindings, like as catching asynchrounous Focus somewhere in heavens ??? – mKorbel May 02 '12 at 15:01
  • Its not always the most comfortable way to catch key events. For example in case you are writing some game where the only visible component is a game scene (or some visual editor with large editing area) - it is pointless to use KeyBindings. The best way is to catch focus on the scene once and just use KeyListener to process incoming events. – Mikle Garin May 02 '12 at 15:22