Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8721209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T07:11:06+00:00 2026-06-13T07:11:06+00:00

Ok, so what i want is the rectangle to always be moving, but when

  • 0

Ok, so what i want is the rectangle to always be moving, but when you press the left and right arrow is changes the direction by either increasing or decreasing the angle. With this code the sqaure moves as it should in the correct direction, but when i press the keys the direction does not change.

import java.awt.*;
import java.awt.Color;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;


public class Fields extends JPanel implements ActionListener, KeyListener{

Timer tm  = new Timer(5, this);
double x = 250, y = 250, vel = 0.2, angle = 90;

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    this.setBackground(Color.BLACK);
    g.setColor(Color.GREEN);
    g.fillRect((int)x, (int)y, 5, 5);

    tm.start();
}
public void keyTyped(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void keyReleased(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void keyPressed(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void actionPerformed(ActionEvent e)
{

    x += (velX * (float)Math.cos(Math.toRadians(angle - 90)));
    y += (velX * (float)Math.sin(Math.toRadians(angle - 90)));

    repaint();
}
public Fields()
{
    this.addKeyListener(this);
}
public static void main(String[] args)
{
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(500, 500);
    Fields fi = new Fields();
    f.add(fi);
    f.setVisible(true);

}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T07:11:07+00:00Added an answer on June 13, 2026 at 7:11 am

    As started in my comments…

    • Don’t start the timer in paintComponent, this method gets called repeatedly and can be called often in quick succession.
    • Use key bindings

    .

    public class TestAnimation01 {
    
        public static void main(String[] args) {
            new TestAnimation01();
        }
    
        public TestAnimation01() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new Fields());
                    frame.setSize(400, 400);
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class Fields extends JPanel implements ActionListener {
    
            Timer tm = new Timer(125, this);
            double x = 250, y = 250, vel = 0.2, angle = 90;
            private int velX = 4;
            private int velY = 4;
    
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                this.setBackground(Color.BLACK);
                g.setColor(Color.GREEN);
                g.fillRect((int) x, (int) y, 5, 5);
            }
    
            public void actionPerformed(ActionEvent e) {
    
                x += (velX * (float) Math.cos(Math.toRadians(angle - 90)));
                y += (velX * (float) Math.sin(Math.toRadians(angle - 90)));
    
                repaint();
            }
    
            public Fields() {
    
                setFocusable(true);
    
                InputMap im = getInputMap(WHEN_FOCUSED);
                ActionMap am = getActionMap();
    
                // left 37
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "goLeft");
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "goRight");
    
                am.put("goLeft", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        angle--;
                        repaint();
                    }
                });
                am.put("goRight", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        angle++;
                        repaint();
                    }
                });
    
                tm.setRepeats(true);
                tm.setCoalesce(true);
                tm.start();
    
                requestFocusInWindow();
    
            }
        }
    }
    

    There’s a bunch of other things you’ve not covered, such as edge conditions (what happens when it leaves the screen) and individual x/y speeds, but I’m sure you’ll work it out

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want my rectangle to rotate in place. But currently it is rotating as
I have a rectangle which want to move using Canvas.SetLeft(rect, x); But I wanna
I want to draw rectangle that is only specified percent high of panel im
I want to draw some Rectangle over a single Image . For example I
I want to apply a Storyboard to my Rectangle Fill like this: <Rectangle Name=MyRectangle
I want to scale my round rectangle and keep it's radius from been changed.
I want to draw string using Graphics with Rectangle border outside the string. This
I want to position four div s relative to another. I have a rectangle
I want to get a .jpg on a canvas, add a rectangle and a
I have a Canvas with a Rectangle : <Canvas> <Rettangle/> </Canvas> And I want

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.