Results 1 to 8 of 8
Like Tree1Likes
  • 1 Post By shall

Thread: Can anyone help me with this moving rectangle?

  1. #1
    mdCollins1 is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Can anyone help me with this moving rectangle?

    Okay, so I made a moving red rectangle that you can control using the arrow keys. I want to make a blue rectangle that the red one cannot go through. I can't even make the blue one appear. Can anyone help?
    Here's the code as is:
    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    public class move_stop extends JPanel implements ActionListener, KeyListener {
    	public static void main(String[] args) {
    		move_stop t = new move_stop();
    		JFrame frame = new JFrame();
    		frame.setTitle("Rectangle");
    		frame.setSize(600, 400);
    		frame.setVisible(true);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.add(t);
    		frame.validate();
    		
    	}
    
    	Timer tm = new Timer(5, this);
    	int x = 0, y = 0, velX= 0, velY = 0;
    	
    	public move_stop()
    	{
    		tm.start();
    		addKeyListener(this);
    		setFocusable(true);
    		setFocusTraversalKeysEnabled(false);
    	}
    	
    	public void paintComponent(Graphics g) 
    	{
    		super.paintComponent(g);
    		g.setColor(Color.RED);
    		g.fillRect(x,  y, 50, 30);
    		repaint();
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		if (x < 0) //These are for the boundaries//
    		{
    			velX = 0;
    			x = 0;
    		}
    		
    		if (x > 550)
    		{
    			velX = 0;
    			x = 550;
    		}
    		
    		if (y < 0) 
    		{
    			velY = 0;
    			y = 0;
    		}
    		
    		if (y > 350)//make sure left and right walls are > instead of <//
    		{
    			velY = 0;
    			y = 350;
    		}
    		
    		x = x + velX;
    		y = y + velY;
    		repaint();
    	}
    	
    	public void keyPressed(KeyEvent e)
    	{
    		int c = e.getKeyCode();
    		
    		if (c == KeyEvent.VK_LEFT)
    		{
    			velX = -1;
    			velY = 0;
    		}
    		if (c == KeyEvent.VK_UP)
    		{
    			velX = 0;
    			velY = -1;
    		}
    		if (c == KeyEvent.VK_RIGHT)
    		{
    			velX = 1;
    			velY = 0;
    		}
    	
    		if (c == KeyEvent.VK_DOWN)
    		{
    			velX = 0;
    			velY = 1;
    		}	
    	}
    	
    	public void keyTyped(KeyEvent e){}
    
    	@Override
    	public void keyReleased(KeyEvent e) {
    		velX = 0;
    		velY = 0;
    	
    		
    	}

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Can anyone help me with this moving rectangle?

    Questions and comments:
    • Where exactly are you stuck?
    • I don't see code where you try to create or draw the blue rectangle anywhere.
    • repaint() has no business being in the paintComponent(...) method. Having it there is potentially dangerous.
    • Where is your animation loop? I've often used a Swing Timer for this. **Edit** oops missed it, and now I see the Timer.
    • You should probably avoid using KeyListeners for Swing applications and instead favor using key bindings. The tutorials will explain what these are, how to use them, and why they are preferred to KeyListeners.

    Luck.

  3. #3
    mdCollins1 is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Re: Can anyone help me with this moving rectangle?

    Quote Originally Posted by Fubarable View Post
    Questions and comments:
    • Where exactly are you stuck?
    • I don't see code where you try to create or draw the blue rectangle anywhere.
    • repaint() has no business being in the paintComponent(...) method. Having it there is potentially dangerous.
    • Where is your animation loop? I've often used a Swing Timer for this. **Edit** oops missed it, and now I see the Timer.
    • You should probably avoid using KeyListeners for Swing applications and instead favor using key bindings. The tutorials will explain what these are, how to use them, and why they are preferred to KeyListeners.

    Luck.
    I tried making the blue rectangle by making another paint component and changing the color/size but it didn't show up?
    How is the repaint dangerous there? I placed it when the rectangle wasn't showing up before the window was resized and left it there after i realized the frame.validate fixes it. I will remove it though.
    Here is where I tried to add the blue rectangle(With no luck)
    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    public class move_stop_wall extends JPanel implements ActionListener, KeyListener {
    	public static void main(String[] args) {
    		move_stop_wall t = new move_stop_wall();
    		JFrame frame = new JFrame();
    		frame.setTitle("Rectangle");
    		frame.setSize(600, 400);
    		frame.setVisible(true);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.add(t);
    		frame.validate();
    		
    	}
    
    	Timer tm = new Timer(5, this);
    	int x = 0, y = 0, velX= 0, velY = 0;
    	
    	public move_stop_wall()
    	{
    		tm.start();
    		addKeyListener(this);
    		setFocusable(true);
    		setFocusTraversalKeysEnabled(false);
    	}
    	
    	public void paintComponent(Graphics g) 
    	{
    		super.paintComponent(g);
    		g.setColor(Color.RED);
    		g.fillRect(x,  y, 50, 30);
    		
    	}
    	public void paintComponent1(Graphics g) 
    	{
    		super.paintComponent(g);
    		g.setColor(Color.BLUE);
    		g.fillRect(x,  y, 100, 50);
    		
    	}
    	
    
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		if (x < 0) //These are for the boundaries//
    		{
    			velX = 0;
    			x = 0;
    		}
    		
    		if (x > 550)
    		{
    			velX = 0;
    			x = 550;
    		}
    		
    		if (y < 0) 
    		{
    			velY = 0;
    			y = 0;
    		}
    		
    		if (y > 350)//make sure left and right walls are > instead of <//
    		{
    			velY = 0;
    			y = 350;
    		}
    		
    		x = x + velX;
    		y = y + velY;
    		repaint();
    	}
    	
    	public void keyPressed(KeyEvent e)
    	{
    		int c = e.getKeyCode();
    		
    		if (c == KeyEvent.VK_LEFT)
    		{
    			velX = -1;
    			velY = 0;
    		}
    		if (c == KeyEvent.VK_UP)
    		{
    			velX = 0;
    			velY = -1;
    		}
    		if (c == KeyEvent.VK_RIGHT)
    		{
    			velX = 1;
    			velY = 0;
    		}
    	
    		if (c == KeyEvent.VK_DOWN)
    		{
    			velX = 0;
    			velY = 1;
    		}	
    	}
    	
    	public void keyTyped(KeyEvent e){}
    
    	@Override
    	public void keyReleased(KeyEvent e) {
    		velX = 0;
    		velY = 0;
    	
    		
    	}
    
    }

  4. #4
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Can anyone help me with this moving rectangle?

    The blue rectangle didn't draw on the screen because you put it in paintcomponent1 and not paintcomponent.
    Fubarable likes this.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Can anyone help me with this moving rectangle?

    Quote Originally Posted by shall View Post
    The blue rectangle didn't draw on the screen because you put it in paintcomponent1 and not paintcomponent.
    Exactly. The Swing paint manager will call paint(...) which will call the paintComponent(...) override. Nothing will call your paintComponent1 method. So what you'll want to do is to draw the blue rectangle in the paintComponent method, but you'll want to use different variables for its position, not x and y which are already being used for the red rect.

  6. #6
    mdCollins1 is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Re: Can anyone help me with this moving rectangle?

    Quote Originally Posted by Fubarable View Post
    Exactly. The Swing paint manager will call paint(...) which will call the paintComponent(...) override. Nothing will call your paintComponent1 method. So what you'll want to do is to draw the blue rectangle in the paintComponent method, but you'll want to use different variables for its position, not x and y which are already being used for the red rect.


    Thank you. I know i need to keep it under the same paint component. Can you explain how to create another shape within the same paint component?
    I've tried this :
    Java Code:
    public void paintComponent(Graphics g, Graphics g2)
    
    	{
    		super.paintComponent(g);
    		g.setColor(Color.RED);
    		g.fillRect(x,  y, 50, 30);	
    		
    		super.paintComponent(g2);
    		g2.setColor(Color.BLUE);
    		g2.fillRect(0,  0, 50, 30);	
    
    	}
    But i end up with it showing nothing.
    thanks

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Can anyone help me with this moving rectangle?

    You're making it much more difficult than it needs to be, since both rectangles will use the same Graphics object g, and the super.paintComponent needs to be called only once at the start of the method. Something as simple as this could work:

    Java Code:
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.red);
          g.fillRect(redX, redY, RED_WIDTH, RED_HEIGHT);
          
          g.setColor(Color.blue);
          g.fillRect(blueX, blueY, BLUE_WIDTH, BLUE_HEIGHT);
       }
    e.g.,

    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    
    import javax.swing.*;
    
    public class ColoredRectangles extends JPanel {
       private static final int RED_WIDTH = 50;
       private static final int RED_HEIGHT = 30;
       private static final int BLUE_WIDTH = RED_WIDTH;
       private static final int BLUE_HEIGHT = RED_HEIGHT;
       private static final int PREF_W = 600;
       private static final int PREF_H = 400;
       
       private int redX = 25;
       private int redY = 25;
       private int blueX = 100;
       private int blueY = 35;
    
       public ColoredRectangles() {
          // TODO Auto-generated constructor stub
       }
       
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.red);
          g.fillRect(redX, redY, RED_WIDTH, RED_HEIGHT);
          
          g.setColor(Color.blue);
          g.fillRect(blueX, blueY, BLUE_WIDTH, BLUE_HEIGHT);
       }
       
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          ColoredRectangles mainPanel = new ColoredRectangles();
    
          JFrame frame = new JFrame("ColoredRectangles");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Also, please understand that paintComponent is an overridden method, and for it to work, it's method "signature" must match that of the parent, exactly. Meaning, it must have the same number and type parameters. Your paintComponent method has two Graphics object, and is thus not a true override of the parent's method, and will never be called.

  8. #8
    mdCollins1 is offline Member
    Join Date
    Mar 2012
    Posts
    7
    Rep Power
    0

    Default Re: Can anyone help me with this moving rectangle?

    Quote Originally Posted by Fubarable View Post
    You're making it much more difficult than it needs to be, since both rectangles will use the same Graphics object g, and the super.paintComponent needs to be called only once at the start of the method. Something as simple as this could work:

    Java Code:
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.red);
          g.fillRect(redX, redY, RED_WIDTH, RED_HEIGHT);
          
          g.setColor(Color.blue);
          g.fillRect(blueX, blueY, BLUE_WIDTH, BLUE_HEIGHT);
       }
    e.g.,

    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    
    import javax.swing.*;
    
    public class ColoredRectangles extends JPanel {
       private static final int RED_WIDTH = 50;
       private static final int RED_HEIGHT = 30;
       private static final int BLUE_WIDTH = RED_WIDTH;
       private static final int BLUE_HEIGHT = RED_HEIGHT;
       private static final int PREF_W = 600;
       private static final int PREF_H = 400;
       
       private int redX = 25;
       private int redY = 25;
       private int blueX = 100;
       private int blueY = 35;
    
       public ColoredRectangles() {
          // TODO Auto-generated constructor stub
       }
       
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(Color.red);
          g.fillRect(redX, redY, RED_WIDTH, RED_HEIGHT);
          
          g.setColor(Color.blue);
          g.fillRect(blueX, blueY, BLUE_WIDTH, BLUE_HEIGHT);
       }
       
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          ColoredRectangles mainPanel = new ColoredRectangles();
    
          JFrame frame = new JFrame("ColoredRectangles");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Also, please understand that paintComponent is an overridden method, and for it to work, it's method "signature" must match that of the parent, exactly. Meaning, it must have the same number and type parameters. Your paintComponent method has two Graphics object, and is thus not a true override of the parent's method, and will never be called.
    Thank you so much! It finally works.
    (I've just started programming and it becomes difficult to keep up with school)

Similar Threads

  1. Moving a rectangle with a button click
    By vasiqshair in forum Advanced Java
    Replies: 6
    Last Post: 04-15-2012, 12:03 PM
  2. resizing a rectangle?
    By ludis in forum New To Java
    Replies: 9
    Last Post: 12-12-2010, 01:00 PM
  3. Replies: 6
    Last Post: 11-30-2010, 11:29 PM
  4. Wrong with Rectangle res = new Rectangle(0,0,0,0);???
    By jiapei100 in forum AWT / Swing
    Replies: 3
    Last Post: 09-25-2010, 03:39 PM
  5. Construct a rectangle
    By cstokes91 in forum New To Java
    Replies: 1
    Last Post: 01-27-2010, 06:14 AM

Posting Permissions

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