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;
}
}
});