Creating a GUI with JFC/Swing > Perform Custom Painting : Refining the Design最终局部变量如何避免重复调用方法?
我正在阅读上面链接的教程,部分示例代码让我感到困惑。根据该moveSquare
方法中的代码注释,存储位置信息作为最终的局部变量将
“避免重复调用相同 方法”
这使得完全没有意义,我和我希望有人能够阐述评论的意义。 (参见上面的完整的源代码和教程的评论链接)
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);
}
}
+0:所有好东西,我经常使用最终变量出于这些原因,但我会说在这种情况下,每个计数都会失败。 1.我不认为CURR_W比getWidth()更清晰2.调用getWidth()/ getHeight(),但如果条件失败,可能不会使用它们,而是浪费时间而不是帮助。他们最多使用一次,无需任何保存。 3.稍后再调用getX(),getY()等,所以你没有太多保存。恕我直言,IDE重构应该用于重命名方法esp getter与setter。 – 2011-05-10 17:37:02
@Peter,我同意,这个问题的例子是在最终变量中保存结果的一个不好的例子,但是,我试图解释评论背后的含义和可能的优点,但当然不是保证。 – jzd 2011-05-10 17:44:05
谢谢大家的答案...我希望我可以选择多个官方解决方案! – 2011-05-10 17:46:49