gpt4 book ai didi

java - 方法的final局部变量 'avoid repeat invocations'怎么办?

转载 作者:行者123 更新时间:2023-11-29 08:14:01 26 4
gpt4 key购买 nike

Creating a GUI with JFC/Swing > Perform Custom Painting : Refining the Design

我正在阅读上面链接的教程,部分示例代码让我感到困惑。根据moveSquare方法中的代码注释,将位置信息存储为最终局部变量将

'avoid repeat invocations of the same methods'

这对我来说完全没有意义,我希望有人能解释一下评论的含义。 (请参阅上面的链接以获取完整的源代码和教程评论)

class MyPanel extends JPanel {

RedSquare redSquare = new RedSquare();

public MyPanel() {

setBorder(BorderFactory.createLineBorder(Color.black));

addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
moveSquare(e.getX(),e.getY());
}
});

addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent e){
moveSquare(e.getX(),e.getY());
}
});

}

private void moveSquare(int x, int y){

// Current square state, stored as final variables
// to avoid repeat invocations of the same methods.
final int CURR_X = redSquare.getX();
final int CURR_Y = redSquare.getY();
final int CURR_W = redSquare.getWidth();
final int CURR_H = redSquare.getHeight();
final int OFFSET = 1;

if ((CURR_X!=x) || (CURR_Y!=y)) {

// The square is moving, repaint background
// over the old square location.
repaint(CURR_X,CURR_Y,CURR_W+OFFSET,CURR_H+OFFSET);

// Update coordinates.
redSquare.setX(x);
redSquare.setY(y);

// Repaint the square at the new location.
repaint(redSquare.getX(), redSquare.getY(),
redSquare.getWidth()+OFFSET,
redSquare.getHeight()+OFFSET);
}
}

public Dimension getPreferredSize() {
return new Dimension(250,200);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);

redSquare.paintSquare(g);
}
}

最佳答案

这意味着调用 getX() 或其他方法的结果将保存在一个变量中并重复使用,这样您就不必在每次需要 X 或 Y 时都继续调用这些方法。

这有三个好处:

  1. 由于变量名,代码更具可读性
  2. 由于不必一次又一次地调用这些方法,性能得到了提高
  3. 将来的更改可能会更容易,因为您只需在一个地方更改方法名称。

关于java - 方法的final局部变量 'avoid repeat invocations'怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5953774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com