Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 22 of 22

Thread: Mouselistener issues

  1. #1
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Mouselistener issues

    Hello

    I am making a Chess engine for a school project and i've been having some issues with the mouselistener .
    When I perform a mouse "pressed" event , the code inside the event gets executed 3 times.
    The same for when I release , the code gets executed 3 times.

    Could someone explain what I'm doing wrong?
    Unfortunately I can't copy my code here as my post gets denied ...

    Thanks in advance

    --- Update ---

    This is inside my user interface class:

        public void mousePressed(MouseEvent e){
     
     
              x_pressed = e.getX();
              y_pressed = e.getY();
     
     
     
     
                  if(x_pressed > 62 &&  x_pressed < 558 && y_pressed > 62 && y_pressed < 558) // If the press is within the board
     
                        {
     
     
                           Chess_engine.Square_pressed(x_pressed, y_pressed); // Buffer the piece
     
                        }
     
     
     
        }
        @Override
        public void mouseReleased(MouseEvent e){
     
              x_released = e.getX();
              y_released = e.getY();
     
     
                                if(y_released > 62 &&  y_released < 558 && y_released> 62 && y_released < 558)
     
                          {
     
                             Chess_engine.Square_pressed(y_released, y_released);
                             repaint();
                          }
     
     
     
     
              }

    and the following is in my "Chess_engine" Class:

      public static void Square_pressed(int x , int y)
         {
     
     
                piece_x_coordinate = (int)Math.floor((x-62)/62);
                piece_y_coordinate = (int)Math.floor((y-62)/62);
                System.out.println("x = " + piece_x_coordinate + "y = " + piece_y_coordinate);
     
                piece_buffer = ChessBoard[ piece_x_coordinate][ piece_y_coordinate];  // Chosen piece
                System.out.println(piece_buffer);
     
     
         }
     
         public static void Square_released(int x, int y)
         {
                piece_x_coordinate = (int)Math.floor((x-62)/62);
                piece_y_coordinate = (int)Math.floor((y-62)/62);
     
                ChessBoard[ piece_x_coordinate][ piece_y_coordinate] = piece_buffer;
     
                System.out.println(ChessBoard[ piece_x_coordinate][ piece_y_coordinate]);
         }

    Basically for now I'm just trying to move the pieces just by clicking them and releasing the mouse at the new position .
    The way it works is that when I click on the board , I get my x and y coordinates with e.get_x(); and e.get_y(); .
    Then I work out what square those values correspond to , then see what piece is at that square and finally when I release I want that piece to be copied
    onto the new square.

    Thanks in advance.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Mouselistener issues

    code inside the event gets executed 3 times.
    Has the listener been added 3 times? It will get one call for each time it was added.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    Thanks for the reply .

    No it is written once each.
    I also have declared the following statements:

      @Override
        public void mouseClicked(MouseEvent e){
     
     
     
     
        }
        @Override
        public void mouseDragged(MouseEvent e){
     
     
     
            }
        @Override
        public void mouseEntered(MouseEvent e){}
        @Override
        public void mouseExited(MouseEvent e){}
     
        @Override
        public void mouseMoved(MouseEvent e){
     
     
        }

    Because my UserInterface class which implements the mouselistener doesn't like it if I remove those.
    But they are empty.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Mouselistener issues

    I was talking about calls to the addListener method. Each call will add another listener.
    If you are not sure how many times the call to the add method is made, add a println() statement just before the call that will print a message every time it is called.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    I'm not sure what you mean by addlistener method . I'm still a beginner in java so I apologise for the ignorance .
    Below is the whole class , so perhaps you can point as to where it's being called incorrectly.
    I have already tried adding a print statement to the mouse event and it gets printed 3 times for the press and 3 times when I release the button.


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class UserInterface extends JPanel implements MouseListener, MouseMotionListener {
        static int x_pressed,y_pressed;  // Mouse pressed
        static int x_released, y_released;  // Mouse released
     
        static int Square_size = 60;   // size of the playing square on the board.
        static int Tile_offset = 67;  // Offset coordinates of tile on board
        static int Tile_Spacing = 62;
     
     
        boolean pressed;
        boolean released;
        boolean piece_chosen;
     
                // Declaring the Chess pieces 
     
            // *********************************************
     
            // White
     
     
            Image King_white = new ImageIcon("King_White.png").getImage();
     
     
            Image Queen_white = new ImageIcon("Queen_White.png").getImage();
     
     
            Image Knight_white = new ImageIcon("Knight_White.png").getImage();
     
     
            Image Bishop_white = new ImageIcon("Bishop_White.png").getImage();
     
     
            Image Rook_white = new ImageIcon("Rook_White.png").getImage();
     
     
            Image Pawn_white = new ImageIcon("Pawn_White.png").getImage();
     
     
            // Black
     
            Image King_black = new ImageIcon("King_Black.png").getImage();
     
     
            Image Queen_black = new ImageIcon("Queen_Black.png").getImage();
     
     
            Image  Knight_black = new ImageIcon("Knight_Black.png").getImage();
     
     
            Image Bishop_black = new ImageIcon("Bishop_Black.png").getImage();
     
     
            Image Rook_black = new ImageIcon("Rook_Black.png").getImage();
     
     
            Image Pawn_black = new ImageIcon("Pawn_Black.png").getImage();
     
     
     
            // *********************************************
     
     
     
     
     
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);           // Dunno what this is lol
            this.setBackground(Color.BLACK);   // Window Background
            this.addMouseListener(this);       // Mouselistener
            this.addMouseMotionListener(this); // Motionlistener
     
     
            // Following for() cycles generate a checkered board.
     
            //  *******************************************
     
            for(int vertical = 1; vertical < 9; vertical++)
            {
                for(int horizontal = 1; horizontal < 9; horizontal++)
                {
                    if(!((horizontal + vertical)% 2 == 0)) 
                    {
                        g.setColor(new Color(150,50,30)); //Darker squares
     
                       g.fillRect(62*horizontal, 62*vertical , 60, 60); 
                    }
     
                    else
                    {
                        g.setColor(new Color(250,200,100)); // lighter squares
                        g.fillRect(62*horizontal, 62*vertical , 60, 60); 
                    }
                }
            }
     
            //  ********************************************
     
     
            // Updates the current position of the pieces on the board
     
     
                for(int vertical = 0; vertical < 8; vertical ++ )
                  {
     
                    for(int horizontal = 0 ; horizontal < 8; horizontal ++ )
     
                        {
     
                    switch(Chess_engine.ChessBoard[vertical][horizontal]) // Paints a picture according to the value of the String on each square
     
                                {
     
                                  case "a" : g.drawImage(King_black,  Tile_offset + Tile_Spacing*horizontal, Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "q" : g.drawImage(Queen_black, Tile_offset + Tile_Spacing*horizontal,Tile_offset + Tile_Spacing*vertical, 50, 50, this); break; 
                                  case "b" : g.drawImage(Bishop_black,  Tile_offset + Tile_Spacing*horizontal ,Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "k" : g.drawImage(Knight_black,  Tile_offset + Tile_Spacing*horizontal, Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "r" : g.drawImage(Rook_black,  Tile_offset + Tile_Spacing*horizontal, Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "p" : g.drawImage(Pawn_black,  Tile_offset + Tile_Spacing*horizontal, Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
     
                                  case "A" :  g.drawImage(King_white, Tile_offset + Tile_Spacing*horizontal, Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "Q" :  g.drawImage(Queen_white, Tile_offset + Tile_Spacing*horizontal,Tile_offset +  Tile_Spacing*vertical, 50, 50, this); break;
                                  case "B" :  g.drawImage(Bishop_white, Tile_offset + Tile_Spacing*horizontal,Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "K" :  g.drawImage(Knight_white, Tile_offset + Tile_Spacing*horizontal,Tile_offset + Tile_Spacing*vertical, 50, 50, this); break;
                                  case "R" :  g.drawImage(Rook_white, Tile_offset + Tile_Spacing*horizontal, Tile_offset +  Tile_Spacing*vertical, 50, 50, this); break;
                                  case "P" :  g.drawImage(Pawn_white, Tile_offset + Tile_Spacing*horizontal, Tile_offset +  Tile_Spacing*vertical, 50, 50, this); break;
     
                                  case " " :  break;   // Square is empty    
     
     
     
                               }  // End of switch statement
     
                          }    // End of For loop 1
                     } // End of for loop 2
     
       // End of updating pieces      
     
     
     
       // ************************************
     
     
        }
     
     
     
     
        @Override
        public void mouseMoved(MouseEvent e){
     
     
        }
        @Override
        public void mousePressed(MouseEvent e){
            System.out.println("Pressed");
     
            /*
              x_pressed = e.getX();
              y_pressed = e.getY();
     
     
     
     
                  if(x_pressed > 62 &&  x_pressed < 558 && y_pressed > 62 && y_pressed < 558) // If the press is within the board
     
                        {
     
     
                           Chess_engine.Square_pressed(x_pressed, y_pressed); // Buffer the piece
     
                        }
     
    */
     
        }
        @Override
        public void mouseReleased(MouseEvent e){
     
            System.out.println("Released");
            /*
              x_released = e.getX();
              y_released = e.getY();
     
     
                                if(y_released > 62 &&  y_released < 558 && y_released> 62 && y_released < 558)
     
                          {
     
                             Chess_engine.Square_pressed(y_released, y_released);
                             repaint();
                          }
     
     
     
                  */
              }
     
     
     
     
     
        @Override
        public void mouseClicked(MouseEvent e){
     
     
     
     
        }
        @Override
        public void mouseDragged(MouseEvent e){
     
     
     
            }
        @Override
        public void mouseEntered(MouseEvent e){}
        @Override
        public void mouseExited(MouseEvent e){}
     
     
     
     
     
     
     
     
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Mouselistener issues

    These are calls to the add listener methods:
      this.addMouseListener(this);       // Mouselistener
      this.addMouseMotionListener(this); // Motionlistener
    A listener will be added each time those methods are called.
    The calls to the add listener methods should only be done ONE time. The paintComponent() method can be called many times a second. Don't add code to that method that should only be done one time.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    I see ,
    So they way I understand it is that the add listener methods add a listener every time they are called so I should remove them from the paintComponent() method?
    Where should I put them then.

    Thanks in advance

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    Typically in the constructor.

  9. #9
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    In the constructor of the Userinterface class?
    I have it defined like this :


    public static void main(String[] args) {

    JFrame f = new JFrame("Chess graphix");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Finishes program when Cross is pressed on window
    UserInterface ui = new UserInterface(); // Creates instance of user interface class
    f.add(ui); // Adds instance of the user interface class
    f.setSize(800,800); // Size of main window
    f.setVisible(true); // Has to be set true to be visible


    }

    The
     UserInterface ui = new UserInterface();

    is the constructor for the UserInterface class , but there aren't any brackets where to add it .
    Also what would I use as the parameters ?
    Would it be something like

     paintComponent.addMouseListener(this);

    ? Or is that completely wrong.
    I'm not very experienced in object oriented programming , I come from an embedded C background so this is new for me.

    --- Update ---

    ahh , or do I do something like this:

    public class UserInterface extends JPanel implements MouseListener, MouseMotionListener {
     
        UserInterface()   // Constructor
        {
     
            this.addMouseListener(this);       
            this.addMouseMotionListener(this);
     
        }
     
     
       // rest of the code...........

    Will that implement it inside the paintComponent() method? I'm guessing it should since it resides inside the UserInterface class.

    --- Update ---

    Well it seems to be working now with the recent change .
    Thanks alot for the help!

  10. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    You've evolved some. Now that you actually have a constructor, I recommend you review the code you have in the main() method you showed in post #9 and move most of that to the constructor. The main() method should start the GUI on the EDT and that's about it.

  11. #11
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    So the

    f.add(ui); // Adds instance of the user interface class
    f.setSize(800,800); // Size of main window 
    f.setVisible(true); // Has to be set true to be visible

    should be moved to the constructor?

    I'm having issues that I can't call the UserInterface class from my Chess_engine class.
    For example why can only access the variables and methods of the UserInterface class from my main method , but if I try from anywhere else (in the Chess_engine class) then it gives me an error.

    For example if
    Amethod() is a method in my UserInterface class and "ui" is an instance of the class , then shouldn't I be able to access it like this : ui.Amethod(); ?
    It's not working for some reason.

    Perhaps someone could refer me to a good java graphics tutorial?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Mouselistener issues

    It's not working
    Please copy the full text of the error message and paste it here. It has important info about the error.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    My mistake .
    When I said "it's not working" I meant that it shows me a red error on the code line in the IDE . Says 'symbol not found'

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Mouselistener issues

    'symbol not found'
    Sorry, I can't see the "red error" from here.
    What is the symbol that is not found?
    Please copy and post here the source line where that symbol is used that causes the error.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    "Symbol not found" means you've used a variable name that hasn't been declared within the scope you're using it. It's difficult to guide you to a solution without seeing the code, so post the code that is giving you the red line with enough context to see the reason for the error. In fact, post the whole class.

  16. #16
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    I apologize for the confusion.

    What I wanted to do is access a few variables and methods from my UserInterface class.
    It was giving me an error because I was trying to access them through an instance of the class UserInterface like this : ui.x_pressed = 10; ( UserInterface ui = new UserInterface(); )
    But it works now when I try to say : UserInterface.x_pressed = 10;

    Thanks for the help, this object oriented stuff is abit confusing

  17. #17
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    To add to your confusion, this:

    UserInterface.x_pressed = 10;

    is not object-oriented programming (OOP). It's anti-OOP. If you're using that statement in your ChessEngine class (what it should be called), then it's likely plain wrong and going to cause you troubles at some point, or it already has and you just haven't realized it yet.

  18. #18
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    Quote Originally Posted by GregBrannon View Post
    To add to your confusion, this:

    UserInterface.x_pressed = 10;

    is not object-oriented programming (OOP). It's anti-OOP. If you're using that statement in your ChessEngine class (what it should be called), then it's likely plain wrong and going to cause you troubles at some point, or it already has and you just haven't realized it yet.
    You are probably right ,
    My point is not to make this engine in an object-oriented fashion . It's just that I read that the graphics have to be in one class and the engine in another so I need to extract data from one to the other at some point.
    I don't really have that statement in my code , it's just a theoretical question . In case I did need to use it.

    But thanks for your input.

  19. #19
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    It's just that I read that the graphics have to be in one class and the engine in another . . .
    Where did you read this?

  20. #20
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    I just did my graphics in accordance to some chess tutorial on youtube. Granted he doesn't sound like he entirely knows what he is talking about but it works , sortoff and I can't find a better tutorial

  21. #21
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Mouselistener issues

    Okay. It's a statement too broad that may be appropriate in the context of the tutorial, but I recommend you don't accept it as a significant learning point to be applied to future projects. There are really no (or very few) design/architecture "have tos" in Java, but there are recommended approaches, design patterns, etc. It's useful to experience many of them to increase your understanding and to find the approach(es) you find most useful for your style of programming.

    Since chess is a bit more complicated, you might find better tutorials for the game's graphics portion by broadening your search to checkers or other 8 x 8 checkered board games. Even if you stick with this tutorial overall or for the chess logic, it's helpful to view multiple views of the same topic, because everyone has their own agendas, what they think is hard or important, and their focus may not agree with what you need. Not to mention the fact that some (many?) of the tutorials you'll find are just plain crap.

  22. #22
    Member
    Join Date
    Dec 2013
    Posts
    37
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Re: Mouselistener issues

    Thanks for your answer Greg.

    Yeah there are alot of crappy tutorials out there . I've looked through many of them . I already have my basic board layout which I can interact with using a mouse (thanks to you guys) and the pieces move as intended .
    Now I just need to program every piece move and all the rules etc.

    As I mentioned before I come from a background of embedded electronics so this is all relatively new to me . I used to not think much about java but I recently realised what a powerfull tool It can be for my future studies .
    Mostly I am planning to use java as an interface for electronics. Basically Inputting data into a java program and displaying it with graphics . (i'm studying robotics)

    I'd appreciate it if anyone pointed me in the right direction concerning learning java graphics and input/output stream.

Similar Threads

  1. Issues with my ordering program - if statement issues?
    By Shenaniganizer in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 31st, 2012, 10:17 PM
  2. MouseListener
    By Karthik Prabhu in forum AWT / Java Swing
    Replies: 5
    Last Post: June 30th, 2012, 02:18 AM
  3. problem with the MouseListener
    By boaz1001 in forum What's Wrong With My Code?
    Replies: 8
    Last Post: August 23rd, 2011, 07:23 AM
  4. 3Dmouse mouselistener
    By zimzille in forum Java Theory & Questions
    Replies: 0
    Last Post: April 6th, 2011, 03:12 AM
  5. MouseListener
    By _lithium_ in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 18th, 2011, 11:43 AM