Results 1 to 10 of 10
  1. #1
    ohkelvin is offline Member
    Join Date
    Jun 2011
    Posts
    5
    Rep Power
    0

    Exclamation Help!! Trying to write a program that make a square move with keyboard and mouse.

    Hi! I need help with my program, i typed the codes but it is not functioning the way i wanted. Right now, i can move the square with my keyboard arrows keys. But i dont know why my mouse cant drag the square. This is a school project. I was trying to merge 2 project together.

    Here is my code:

    Java Code:
    package helloworld;
    
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    
    
    /*
     * This applet demonstrates Focus events and Key events.  A colored square
     * is drawn on the applet.  By pressing the arrow keys, the user can move
     * the square up, down, left, or right.  By pressing the keys
     * R, G, B, or K, the user can change the color of the square to red,
     * green, blue, or black, respectively.  Of course, none of the keys
     * will have any effect if the applet does not have the keyboard input
     * focus.  The applet changes appearance when it has the input focus.
     * A cyan-colored border is drawn around it.  When it does not have
     * the input focus, the message "Click to activate" is displayed
     * and the border is gray.
     *    This class contains a main() routine; when it is run as a stand-alone
     * application, the same JPanel that is used in the applet is shown in a
     * window instead.
     */
    
    
    public class ShapeMover extends JApplet {
    
        private int x1, y1;   // Coords of top-left corner of the red square.
       /**
        * The main program just opens a window that shows an object of type
        * ContentPanel -- a nested class that is defined in this class.
        */
       public static void main(String[] args) {
          JFrame window = new JFrame("ShapeMover");
          window.setContentPane( new ContentPanel() );
          window.setSize(500,500);
          window.setLocation(100,100);
          window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
          window.setVisible(true);
       }
       
       public ShapeMover() {
           Dragger listener = new Dragger();  // Listening object, belonging to a nested
                                             //     class that is defined below.
          
          addMouseListener(listener);        // Set up listening.
          addMouseMotionListener(listener);
       }
       
       private class Dragger implements MouseListener, MouseMotionListener {
          
          /* Some variables used during dragging */
          
          boolean dragging;      // Set to true when a drag is in progress.
          
          boolean dragRedSquare; // True if red square is being dragged, false
                                 //    if blue square is being dragged.
          
          int offsetX, offsetY;  // Offset of mouse-click coordinates from the
                                 //   top-left corner of the square that was
                                 //   clicked.
    
            public void mouseClicked(MouseEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
    
            public void mousePressed(MouseEvent evt) {
                if (dragging)  // Exit if a drag is already in progress.
                return;
             
             int x = evt.getX();  // Location where user clicked.
             int y = evt.getY();
             
            if (x >= x1 && x < x1+30 && y >= y1 && y < y1+30) {
                   // It's the red square.
                dragging = true;
                dragRedSquare = true;
                offsetX = x - x1;  // Distance from corner of square to (x,y).
                offsetY = y - y1;
             }
             
          }
          
          /**
           * Dragging stops when user releases the mouse button.
           */
    
            public void mouseReleased(MouseEvent evt) {
                dragging = false;
          }
          
          /**
           * Respond when the user drags the mouse.  If a square is 
           * not being dragged, then exit. Otherwise, change the position
           * of the square that is being dragged to match the position
           * of the mouse.  Note that the corner of the square is placed
           * in the same relative position with respect to the mouse that i
           * had when the user started dragging it.
           */
    
            
            public void mouseDragged(MouseEvent evt) {
               if (dragging == false)  
                return;
             int x = evt.getX();
             int y = evt.getY();
             if (dragRedSquare) {  // Move the red square.
                x1 = x - offsetX;
                y1 = y - offsetY;
             }
             repaint();  // (Calls the repaint() method in the DragTwoSquaresPanel class.)
          }
            
            public void mouseEntered(MouseEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
    
            public void mouseExited(MouseEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
    
    
            public void mouseMoved(MouseEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
          
          /**
           * Respond when the user presses the mouse on the panel.
           * Check which square the user clicked, if any, and start
           * dragging that square.
           */
       
       /**
        * The init() method of the applet just sets the content pane
        * of the applet to be a panel of type ContentPanel, a nested class
        * that is defined in this class and which does all the work.
        */
       }
       public void init() {
          setContentPane( new ContentPanel() );
       }
       
       
       public static class ContentPanel extends JPanel
                      implements KeyListener, FocusListener, MouseListener {
          
             // (Note:  MouseListener is implemented only so that
             //         the applet can request the input focus when
             //         the user clicks on it.)
          
          private static final int SQUARE_SIZE = 40;  // Length of side of square.
          
          private Color squareColor;  // The color of the square.
          
          private int x1, y1;  // Coordinates corner of square.
    
          /**
           * The constructor sets the initial position and color of the square
           * and registers itself to act as a listener for Key, Focus, and 
           * Mouse events.
           */
          public ContentPanel() {
             
             y1 = 200;  // Initial position of top-left corner of square.
             x1 = 200;
             squareColor = Color.RED;  // Initial color of square.
             
             setBackground(Color.WHITE);
    
             addKeyListener(this);     // Set up event listening.
             addFocusListener(this);
             addMouseListener(this);
             
          } // end init();
          
          
          /**
           * Draws a border, square, and message in the panel.  The message and
           * the color of  the border depend on whether or not the pane has
           * the input focus.
           */
          public void paintComponent(Graphics g) {
             
             super.paintComponent(g);  // Fills the panel with its
                                       // background color, which is white.
             
             /* Draw a 3-pixel border, colored cyan if the applet has the
                keyboard focus, or in light gray if it does not. */
             
             if (hasFocus()) 
                g.setColor(Color.BLACK);
             else
                g.setColor(Color.LIGHT_GRAY);
             
             int width = getSize().width;  // Width of the applet.
             int height = getSize().height; // Height of the applet.
             g.drawRect(0,0,width-1,height-1);
             g.drawRect(1,1,width-3,height-3);
             g.drawRect(2,2,width-5,height-5);
             
             /* Draw the square. */
             
             g.setColor(squareColor);
             g.fillRect(x1, y1, SQUARE_SIZE, SQUARE_SIZE);
             
             /* Print a message that depends on whether the panel has the focus. */
             
             g.setColor(Color.BLUE);
             if (hasFocus()) {
                g.drawString("Arrow Keys Move Square",7,20);
                g.drawString("Y, R, G, B Change Color",7,40);
             }
             else
                g.drawString("Click to activate",7,20);
             
          }  // end paintComponent()
    
          
          // ------------------- Event handling methods ----------------------
    
          /**
           * This will be called when the panel gains the input focus.  It just
           * calls repaint().  The panel will be redrawn with a cyan-colored border
           * and with a different message.
           */
          public void focusGained(FocusEvent evt) {
             repaint();  // redraw with cyan border
          }
          
          
          /**
           * This will be called when the panel loses the input focus.  It just
           * calls repaint().  The panel will be redrawn with a gray-colored border
           * and with the message "Click to activate."
           */
          public void focusLost(FocusEvent evt) {
             repaint();  // redraw without cyan border
          }
          
          
          /**
           * This method is called when the user types a character on the keyboard
           * while the panel has the input focus.  If the character is R, G, B, or K
           * (or the corresponding lower case characters), then the color of the
           * square is changed to red, green, blue, or black, respectively.
           */
          public void keyTyped(KeyEvent evt) {
             
             char ch = evt.getKeyChar();  // The character typed.
             
             if (ch == 'B' || ch == 'b') {
                squareColor = Color.BLUE;
                repaint();   // Redraw panel with new color.
             }
             else if (ch == 'G' || ch == 'g') {
                squareColor = Color.GREEN;
                repaint();
             }
             else if (ch == 'R' || ch == 'r') {
                squareColor = Color.RED;
                repaint();
             }
             else if (ch == 'Y' || ch == 'y') {
                squareColor = Color.YELLOW;
                repaint();
             }
             
          }  // end keyTyped()
          
          
          /**
           * This is called each time the user presses a key while the panel has
           * the input focus.  If the key pressed was one of the arrow keys,
           * the square is moved (except that it is not allowed to move off the
           * edge of the panel).
           */
          public void keyPressed(KeyEvent evt) { 
             
             int key = evt.getKeyCode();  // keyboard code for the pressed key
             
             if (key == KeyEvent.VK_LEFT) {
                x1 -= 8;
                if (x1 < 3)
                   x1 = 3;
                repaint();
             }
             else if (key == KeyEvent.VK_RIGHT) {
                x1 += 8;
                if (x1 > getWidth() - 3 - SQUARE_SIZE)
                   x1 = getWidth() - 3 - SQUARE_SIZE;
                repaint();
             }
             else if (key == KeyEvent.VK_UP) {
                y1 -= 8;
                if (y1 < 3)
                   y1 = 3;
                repaint();
             }
             else if (key == KeyEvent.VK_DOWN) {
                y1 += 8;
                if (y1 > getHeight() - 3 - SQUARE_SIZE)
                   y1 = getHeight() - 3 - SQUARE_SIZE;
                repaint();
             }
             
          }  // end keyPressed()
          
          
          /**
           * This is called each time the user releases a key while the panel
           * has the input focus.  In this class, it does nothing, but it is
           * required to be here by the KeyListener interface.
           */
          public void keyReleased(KeyEvent evt) {
          }
          
          
          /**
           * This is called when the user clicks the panel with the mouse.
           * It just requests that the input focus be given to the panel.
           */
          public void mousePressed(MouseEvent evt) {
                      
              requestFocus();
             
        
             } 
                
          public void mouseEntered(MouseEvent evt) { }  // Required by the
          public void mouseExited(MouseEvent evt) { }   //    MouseListener
          public void mouseReleased(MouseEvent evt) { } //       interface.
          public void mouseClicked(MouseEvent evt) { }
          
       } // end nested class ContentPanel
    
    }
     // end class KeyboardAndFocusDemo

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    It's a lot of code, but a quick glance shows that you never create an instance of shape mover, you also don't use the dragger class anywhere thats useful.

    You create dragger listener, in the shapemover constructor but I don't see shape mover being initialized.

  3. #3
    ohkelvin is offline Member
    Join Date
    Jun 2011
    Posts
    5
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    You create dragger listener, in the shapemover constructor but I don't see shape mover being initialized.
    what do you mean by shape mover not being intialized?

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I could have missed it, but I don't see you ever creating an instance of the shapemover class, and the ShapeMover constructor is where the dragger is made.

  5. #5
    ohkelvin is offline Member
    Join Date
    Jun 2011
    Posts
    5
    Rep Power
    0

    Default

    I'm sorry, but how can I add an instance for the shaemover class then, sry i am still new to java

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    It won't be very easy, but, you need to somehow create an instance of the shape mover class, the shapemover classes constructor will initialize the dragger for you. In main the only class you created is the content panel.

  7. #7
    ohkelvin is offline Member
    Join Date
    Jun 2011
    Posts
    5
    Rep Power
    0

    Default

    Quote Originally Posted by sunde887 View Post
    It won't be very easy, but, you need to somehow create an instance of the shape mover class, the shapemover classes constructor will initialize the dragger for you. In main the only class you created is the content panel.
    I'm very sorry but i still dont get how do i create an instance, what do i exactly need to type to create an instance.... ):

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

    Default

    Creating "an instance of" is just another way of saying to create a ShapeMover object, but before even doing that... have you changed your code in any way since you've posted it? Is this code supposed to create a free-standing GUI (a JFrame) or a JApplet?

  9. #9
    ohkelvin is offline Member
    Join Date
    Jun 2011
    Posts
    5
    Rep Power
    0

    Default

    Its for a JApplet, and i havent changed any yet

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

    Default

    Looking at your code in more detail, you seem to have two MouseListener-type classes,
    • Dragger which you seem to have "borrowed" from somewhere else, I'm guessing code you've found on-line and which you appear to be adding directly to an applet object in its constructor, a constructor which is never called, and which never should be called, and ...
    • ContentPanel, which has skeleton code for MouseListener and MouseMotionListener which appears to have been given to you by your teacher which you've not yet fleshed out, which appears to be added appropriately to the ContentPanel JPanel object.


    Suggestion: don't blindly "borrow" code from the internet without understanding it. Get rid of that code (Dragger) and read the MouseListener tutorial so you can write your own MouseListener in the ContentPanel class as your teacher likely intended you to do. If you still get stuck after reading the tutorials and after putting in a decent effort of your own to create a MouseListener/MouseMotionListener, please come on back with your own code, and we'll gladly help you as best we can.

    Some useful tutorial links: How to Write a MouseListener
    How to Write a MouseMotionListener
    Last edited by Fubarable; 06-17-2011 at 05:53 AM.

Similar Threads

  1. Replies: 1
    Last Post: 06-08-2011, 10:22 PM
  2. how to move an image automatically without using mouse
    By saranyabaskaran in forum New To Java
    Replies: 6
    Last Post: 03-19-2011, 10:00 AM
  3. Bluetooth mouse/keyboard emulation
    By matech in forum Advanced Java
    Replies: 0
    Last Post: 01-29-2011, 04:40 PM
  4. Replies: 1
    Last Post: 10-30-2009, 06:47 AM
  5. locking keyboard and mouse
    By vibhor in forum AWT / Swing
    Replies: 4
    Last Post: 02-26-2009, 11:12 PM

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
  •