2015-11-05 90 views
0

所以我在java中做了一個畫圖應用程序。然而,不要點擊並按住,然後拖動來畫東西。相反,我想點擊激活我的畫筆/筆,它將繪製到我帶上鼠標的位置,然後再次單擊以取消激活畫筆/筆。點擊激活筆的Java畫圖

public class DrawArea extends JComponent { 

private Image image; 
private Graphics2D g2; 

// Mouse coordinates 
private int currentX, currentY, oldX, oldY;  


public DrawArea() { 

addMouseListener(new MouseAdapter() { 
    public void mousePressed(MouseEvent e) { 
     // save coord x,y when mouse is pressed 
     oldX = e.getX(); 
     oldY = e.getY(); 
    } 
}); 

addMouseMotionListener(new MouseMotionAdapter() { 
    public void mouseDragged(MouseEvent e) { 
     // coord x,y when drag mouse 
     currentX = e.getX(); 
     currentY = e.getY(); 

     if (g2 != null) { 
     // draw oval if g2 context not null 
     g2.drawOval(oldX, oldY, 20, 20); 
     g2.fillOval(oldX, oldY, 20, 20); 

     // refresh draw area to repaint 
     repaint(); 
     // store current coords x,y as olds x,y 
     oldX = currentX; 
     oldY = currentY; 
     } 
    } 
}); 

回答

0

創建一個變量,當您單擊時激活,直到您再次單擊,將該變量設置爲false。這就是我所做的。