0

I have found loads of questions on this website on how to use getter functions in java but I haven't found many real answers to most of these questions which is why I am asking this.

Here is a piece of my code:

y - Height of shape

x - Width of shape

posX - Position of shape on x axis

posY - Position of shape on y axis

speed - Speed travelling

speedY - Equal to speed, specially made for movement on y axis

halfY - Half of y and distance shape should move down before turning around

public void actionPerformed(ActionEvent e){
    if(posY == 0){
        posX = posX + speed;
    }
    if((posX <= 0)&&(posY != 0)){
        posX = posX + speed - speed;
        posY = posY + speedY;
    }
    if(posX >= 600 - x){
        posX = posX + speed - speed;
        posY = posY + speedY;       
    }
    if(posY >= y - halfY){
        posX = posX - speed;
    }
    repaint();
}

After moving I want to get the current y position of the shape and use it in another method, but I am unsure how to do this and this is also a void function so I am unsure how to get the y and use it in another method IN THE SAME CLASS.

user62
  • 43
  • 9

2 Answers2

2

Let's say that you have a class that resembles the following

public class Point {
    // This fields can't be accessed outside of this class
    private int x;
    private int y;

    /*....More code...*/

    // To be able to update and acces the fields x and y from the outside  
    // you need getters and setters.

    // The getters
    public int getX(){
        return this.x;
    }

    public int getY(){
        return this.y;
    }

    // The setters
    public void setX(int new_x){
        this.x = new_x;
    }

    public void setY(int new_y){
        this.y = new_y;
    }
}

Your updated code would now look like.

public void actionPerformed(ActionEvent e){
    if(pos.getX() == 0){
        pos.setX(pos.getX() + speed);
    }
    else if((pos.getX() <= 0) && (pos.getY() != 0)){
        pos.setX(pos.getX() + speed - speed);
        pos.setY(pos.getY() + speedY);
    }
    else if(pos.getX() >= 600 - x){
        pos.setX(pos.getX() + speed - speed);
        pos.setY(pos.getY() + speedY);       
    }
    else if(pos.getY() >= y - halfY){
        pos.getX(pos.getX() - speed);
    }
    repaint();
}

Where pos is an instance of Point.

Remy J
  • 709
  • 1
  • 7
  • 18
1

Here's a basic getter function for you (assumes your posX/Y are points)

public Point getX() { return this.posX; }

public Point getY() { return this.posY; }

If you want to call this in another class using instances of whatever this class is, then simply do objectname.getX/Y();

Furthermore, if these positions are instance data, (which they should be), you could call objectname.posX/Y;, although I prefer to use methods unless necessary.

If this doesn't answer your question, please include the entire class and a more detailed description of what you're trying to do.

Hope I helped.

AGushin
  • 26
  • 4