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