【问题标题】:How to use a getY() method in java?如何在 java 中使用 getY() 方法?
【发布时间】:2017-04-13 04:48:42
【问题描述】:

我在这个网站上发现了很多关于如何在 java 中使用 getter 函数的问题,但我没有找到大多数这些问题的真正答案,这就是我问这个的原因。

这是我的一段代码:

y - 形状高度

x - 形状的宽度

posX - 形状在 x 轴上的位置

posY - 形状在 y 轴上的位置

速度 - 速度旅行

speedY - 等于速度,专为y轴移动而设计

halfY - y 的一半和距离形状应在转身前向下移动

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();
}

移动后,我想获取形状的当前 y 位置并在另一种方法中使用它,但我不确定如何执行此操作,这也是一个 void 函数,因此我不确定如何获取 y 并使用它在同一类中的另一种方法中。

【问题讨论】:

  • 请帮帮我。
  • 首先你需要使用setter方法setY()或者构造函数然后你可以调用getY()方法。
  • 这就是 getter 的确切用途。为 posY 和 posX 创建 getter 方法
  • 您的变量posY 不是局部变量。它可能是一个成员变量。实现getY() 以返回它。拨打getY()获取。
  • + 速度 - 速度 ---> 为什么会这样?这是没有意义的

标签: java methods actionlistener getter


【解决方案1】:

假设您有一个类似于以下的类

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;
    }
}

您更新后的代码现在看起来像。

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();
}

其中posPoint 的一个实例。

【讨论】:

    【解决方案2】:

    这是一个基本的 getter 函数(假设你的 posX/Y 是点)

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

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

    如果你想使用这个类的实例在另一个类中调用它,那么只需执行 objectname.getX/Y();

    此外,如果这些位置是实例数据,(它们应该是),您可以调用 objectname.posX/Y;,尽管除非必要,我更喜欢使用方法。

    如果这不能回答您的问题,请附上整个课程并更详细地说明您正在尝试做什么。

    希望我能帮上忙。

    【讨论】:

    • 感谢您的帮助。
    • 没问题!乐于助人。 :)
    • 我们使用 object.getY() 而不是 object.posY 是有原因的。这个原因与封装概念有关。 stackoverflow.com/a/19044735/7011883
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 2016-03-02
    • 2011-04-06
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多