我在这个网站上发现了很多关于如何在 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 并使用它在同一个类中的另一种方法中。
最佳答案
假设您有一个类似于以下内容的类
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();
}
其中 pos
是 Point
的实例。
关于java - 如何在java中使用getY()方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43379060/