Results 1 to 2 of 2
  1. #1
    samm46 is offline Member
    Join Date
    Dec 2015
    Rep Power

    Question Java Newbie Help

    Hello everyone,

    Recently I have been trying to learn java and created this simple program where a rectangle is supposed to move depending on what arrow key the users presses. I wrote this code and wonder why it doesn't seem to work.

    My problem is that the rectangle is not moving. Why is this? As I mentioned earlier in the title that I am a complete noob and I know there must've been some stupid mistake. Thanks!

    Please help.

    Java Code:
    package lex;
    import java.awt.Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class Main extends JPanel{
        static int myX = 400; // Setting cords for player x and y
        static int myY = 400;
    	   public static void main(String[] a) {
    		      JFrame f = new JFrame();
    		      f.setSize(400, 400);
    		      f.add(new Main());
    		        f.addKeyListener(new KeyAdapter() {
    		            public void keyPressed(KeyEvent e) {
    		   public void paint(Graphics g) {
    		      g.fillRect (myX, myY, 50, 75);
        public static void moveIt(KeyEvent evt) {
            switch (evt.getKeyCode()) {
                   case KeyEvent.VK_DOWN:
                       myY += 5;
                   case KeyEvent.VK_UP:
                       myY -= 5;
                   case KeyEvent.VK_LEFT:
                       myX -= 5;
                   case KeyEvent.VK_RIGHT:
                       myX += 5;

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Java Newbie Help

    You need to override paintComponent(Graphics g) and put your rectangle code in there. Then each time you make a change to the coordinates, you need to call repaint.

    Also, you first statement in your paintComponent(Graphics g) should be super.paintComponent(g).

    I recommend you read up on painting in the tutorials in my signature.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. java newbie
    By jrooi1 in forum Introductions
    Replies: 0
    Last Post: 04-17-2012, 02:10 PM
  2. newbie to java
    By mark clarke in forum New To Java
    Replies: 1
    Last Post: 08-01-2011, 10:48 PM
  3. (Newbie) Help with Java and XML
    By sharktopus in forum AWT / Swing
    Replies: 0
    Last Post: 05-15-2011, 06:54 PM
  4. Newbie to Java.
    By avinash87 in forum New To Java
    Replies: 2
    Last Post: 04-30-2011, 09:36 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts