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 10 of 10

Thread: Help with get and set

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default [SOLVED]Help with get and set

    Hi guys,

    Ok so I have to do a Pong type game for school.

    So far, I am doing it with a mousemotion listener. But the thing is, I have 2 classes, Raquette and Ball.

    the Raquette class contains the mousemotion listener for the paddle. The Ball gets refreshed using a thread.

    So I made a isHiT() method in my Ball class to see if the raquette and teh Ball comes in contact.

    But the problem is that the getY() keeps returning 0 even tough I am refresshing it....

    Here is the code:

     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /**
     * Travail fait par Aravinthan Sivaneswaran
     * Date: 17-Nov-2011
     * Nom du projet:
     */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseEvent;
     
    //classe démarrage
    public class main {
     
        public static void main(String[] args) {
            JFrame frame = new BounceThreadFrame();
            frame.setVisible(true);
        }
    }
     
    //classe de la fenêtre graphique
    class BounceThreadFrame extends JFrame {
     
        private JPanel canvas;
        int x = 0;
        private int addY = 0;
     
        public BounceThreadFrame() {
            setSize(400, 400);
            setResizable(false);
            setLocationRelativeTo(null);  //laisse l'OS placer la fenêtre
            setTitle("Bounce");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            canvas = new JPanel();
     
            getContentPane().add(canvas, "Center");
            JButton b = new JButton("Lancer balle");
            getContentPane().add(b, "North");
     
     
            b.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent evt) {
     
                    if (x == 0) {
                        Ball b = new Ball(canvas);
                        Raquette r = new Raquette(canvas);
                        b.start();  //pour exécuter la méthode run() du thread
                        r.draw();
                        r.start();
                    }
     
                    x++;
                }
            });
     
        }
    }
     
    //classe Balle hérite de Thread
    class Ball extends Thread {
     
        private JPanel box;  //panneau supportant la balle
        private static final int XSIZE = 20, YSIZE = 20;//dimensions balle
        private int x = 0, y = 0;  //position initiale balle
        private int dx = 4; //déplacement balle (horizontal)
        private int dy = 4;
        public boolean notout = true;
     
        Raquette r = new Raquette(box);
     
        public Ball(JPanel b) {
            box = b;
        }
     
        // exécution du thread (déclenché par start)
        public void run() {
            try {
                while (notout) {
                    sleep(20); //attendre 5 ms
                    move();   //déplacer balle
     
                }
            } catch (InterruptedException e) {
            }
        }
     
        //méthode déplacer balle
        public void move() {
            Graphics g = box.getGraphics();
            Dimension d = box.getSize();
            g.setXORMode(box.getBackground());//pour que les pixels retrouvent leur couleur d'origine lors du 2ème dessin (qui suit)
            g.fillOval(x, y, XSIZE, YSIZE); // on dessine la balle
     
            x += dx;  //on augmente l'abcisse pour déplace la balle horizontalement
            y += dy;
     
            if (x < 1) {
                dx = -dx;
            }
            if (y < 1) {
                dy = -dy;
            }
            if ((x + XSIZE) > d.width) {
                //.showMessageDialog(null, "La balle est sorti. Vous perdez 1 vie", "Vie perdu", JOptionPane.INFORMATION_MESSAGE);
                //notout = false;
                dx = -dx;
            }
            if ((y + YSIZE) > d.height) {
                dy = -dy;
            }
     
            //System.out.println(isHIT());
            if(isHIT()){
                dx = -dx;
                dy = -dy;
            }
     
            g.fillOval(x, y, XSIZE, YSIZE);  //on redessine
     
        }
     
        public boolean isHIT() {
            int raquettey;
     
            raquettey = r.getY();
            System.out.println(raquettey);
            if((y>raquettey && y<(raquettey+r.getYSIZE())) && (x>=box.getWidth()-r.getXSIZE()))
                return true;
            else
                return false;
        }
    } //fin classe balle
     
    //classe Balle hérite de Thread
    class Raquette extends Thread implements MouseMotionListener {
     
        private JPanel box;  //panneau supportant la balle
        private static final int XSIZE = 10, YSIZE = 50;//dimensions balle
        private int x = 385, y = 0;  //position initiale balle
        private int dx = 2; //déplacement balle (horizontal)
        private int dy = 2;
        private int addY;
     
        public Raquette(JPanel r) {
            box = r;
        }
     
        // exécution du thread (déclenché par start)
        public void run() {
            try {
                while (true) {
                    sleep(10); //attendre 5 ms
                    move();   //déplacer balle
     
     
                }
            } catch (InterruptedException e) {
            }
        }
        //méthode déplacer balle
     
        public void draw() {
            Graphics g = box.getGraphics();
            Dimension d = box.getSize();
            g.setXORMode(box.getBackground());//pour que les pixels retrouvent leur couleur d'origine lors du 2ème dessin (qui suit)
            g.fillRect(x, y, XSIZE, YSIZE); // on dessine la balle
        }
     
        //méthode déplacer balle
        public void move() {
            box.addMouseMotionListener(this);
            Graphics g = box.getGraphics();
            Dimension d = box.getSize();
            g.setXORMode(box.getBackground());//pour que les pixels retrouvent leur couleur d'origine lors du 2ème dessin (qui suit)
            g.fillRect(x, y, XSIZE, YSIZE); // on dessine la balle
     
            y = addY;
     
            if (y <= 0) {
                y = 0;
            }
            if ((y + (YSIZE)) > d.height) {
                y = d.height - YSIZE;
            }
     
            setY(y);
            g.fillRect(x, y, XSIZE, YSIZE);  //on redessine
     
        }
     
        void eventOutput(String eventDescription, MouseEvent e) {
            addY = (e.getY());
        }
     
        public void mouseMoved(MouseEvent e) {
            eventOutput("Mouse moved", e);
        }
     
        public void mouseDragged(MouseEvent e) {
            eventOutput("Mouse dragged", e);
        }
     
        public void setY(int y){
            this.y = y;
        }
     
        public int getY(){
            return this.y;
        }
     
        public int getXSIZE(){
            return this.XSIZE;
        }
     
        public int getYSIZE(){
            return this.YSIZE;
        }
    } //fin classe raquette
    Last edited by AraHabs; November 20th, 2011 at 12:46 PM. Reason: Solved


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with get and set

    Try debugging your code by adding printlns to show the values of variables as their values are changed.
    The output should show when the variable has been given a good value and when it has been set to zero.

  3. #3
    Junior Member
    Join Date
    Oct 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with get and set

    I placed a println Right after the setY() in the class Raquette and it showed the right value.
    I placed a println Before using the getY() in the class Ball and it shows 0.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with get and set

    Add printlns to the constructors to show when each class is created and how many of them.

    You could use the 'this' variable in the printlns to get an id for each class.

  5. #5
    Junior Member
    Join Date
    Oct 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with get and set

    I added a println in teh constructors like you said.

    So it gives this:
        public void setY(int a){
            this.y = a;
            System.out.println("SET"+this.y);
        }
     
        public int getY(){
            System.out.println("GET"+this.y);
            return this.y;
        }

    The set gives me the correct value.
    But the get keeps returning 0...

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with get and set

    How many instances of the class were created?
    For which instance is the setY method called?
    For which instance is the getY method called?
    Add a 'this' to the printlns to see:
    System.out.println(this + " SET y="+y);
    System.out.println(this + " GET y="+y);

    Look at what is printed out.

  7. #7
    Junior Member
    Join Date
    Oct 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with get and set

    Ok,
    So when I have the get in my class Ball, the get returns 0.
    So to try it out, I took out the get in the class Ball and put a get right after the set.

    And it returns the right number.

    A part of the printed section:
    Thread[Thread-4,6,main] GET y=0
    Thread[Thread-5,6,main] SET y=0
    Thread[Thread-5,6,main] GET y=0
    Thread[Thread-5,6,main] SET y=4
    Thread[Thread-5,6,main] GET y=4
    Thread[Thread-4,6,main] GET y=0
    Thread[Thread-5,6,main] SET y=8
    Thread[Thread-5,6,main] GET y=8
    Thread[Thread-5,6,main] SET y=14
    Thread[Thread-5,6,main] GET y=14
    Thread[Thread-4,6,main] GET y=0
    Thread[Thread-5,6,main] SET y=17
    Thread[Thread-5,6,main] GET y=17
    Thread[Thread-5,6,main] SET y=20
    Thread[Thread-5,6,main] GET y=20
    The Thread-4 is my Ball class and the Thread 5 is in my Raquette class.
    Could the thread be intefering in this?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with get and set

    You have two instances of a class. You call setY for one and change it's y value.
    When you call getY you get the y value from the other instance of the class which is never changed from 0.

    Can you change the code so there is only one class that everyone uses?

  9. #9
    Junior Member
    Join Date
    Oct 2011
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with get and set

    Ok yeah, I get it.

    I will try to do it and let you know.

    EDIT:

    It works!! Thanks alot!!!

    Thanks for your help,
    Ara
    Last edited by AraHabs; November 20th, 2011 at 12:45 PM. Reason: Finished

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Help with get and set

    It should be better if you do the set and get on the same instance instead of different ones.