我基本上試圖做一些經典的「Paint」(微軟的程序)。但是我想在繪畫時使用圖層。我以爲我可以使用JPanel組件作爲圖層。在java上分層繪畫?
我正在測試下面的代碼。目標是用鼠標繪製一個矩形。在拖動鼠標的同時繪製一個臨時層(temp),並在鼠標釋放時繪製實際的圖層(區域)。但每次我開始繪製一個新的矩形,舊的都消失了。此外,如果我執行setVisible(false)並再次爲true,則一切消失。
MouseInputAdapter mia = new MouseInputAdapter() {
private int startx = 0, starty = 0, stopx = 0, stopy = 0;
public void mousePressed(MouseEvent evt) {
startx = evt.getX();
starty = evt.getY();
}
public void mouseDragged(MouseEvent evt) {
Graphics2D tempg = (Graphics2D) temp.getGraphics();
int width = Math.abs(startx - evt.getX());
int height = Math.abs(starty - evt.getY());
int x = evt.getX(), y = evt.getY();
if(x > startx)
x = startx;
if(y > starty)
y = starty;
Rectangle r = new Rectangle(x, y, width, height);
tempg.clearRect(0, 0, getWidth(), getHeight());
tempg.draw(r);
}
public void mouseReleased(MouseEvent evt) {
Graphics2D g = (Graphics2D) area.getGraphics();
stopx = evt.getX();
stopy = evt.getY();
int width = Math.abs(startx - stopx);
int height = Math.abs(starty - stopy);
int x = startx, y = starty;
if(x > stopx)
x = stopx;
if(y > stopy)
y = stopy;
Rectangle r = new Rectangle(x, y, width, height);
g.draw(r);
}
};
area.addMouseListener(mia);
area.addMouseMotionListener(mia);
temp.addMouseListener(mia);
temp.addMouseMotionListener(mia);
該代碼有什麼問題?
問:該代碼有什麼問題?答:getGraphics() – kleopatra 2012-02-12 09:34:32