我想在點擊鼠標後重新繪製一個方形,但重新繪製方法將被渲染10次。在java swing中重新繪製一個組件
例如在正方形是在X,Y,將在鼠標點擊後重新繪製:
- X + 1,Y + 1
- X + 2,Y + 2
- X + 3,Y + 3
- ...
- ...
- X + 10,Y + 10
我試圖循環重繪方法10次,但結果是最終的油漆,而不是整個過程。
public MyPanel()
{
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
for(int i=0;i<10;i++)
moveSquare(redSquare.getX(),redSquare.getY());
}
});
}
private void moveSquare(int x, int y)
{
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;
// 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+1);
redSquare.setY(y+1);
// Repaint the square at the new location.
repaint(redSquare.getX(), redSquare.getY(),
redSquare.getWidth()+OFFSET,
redSquare.getHeight()+OFFSET);
}
你能顯示你試過的代碼嗎? – exception1
也發佈您的代碼與您的問題 – Engineer
我附上的代碼。 –