2012-11-27 65 views
2

嗨,我需要幫助我正在嘗試製作一個程序,我可以用鼠標在窗口中繪製。到目前爲止,我已經在點擊一個點出現的地方,但我需要添加一個拖動方法,這樣當我拖動鼠標在頁面上繪製東西。有人可以看我的代碼,並幫助我在哪裏可以?用鼠標繪圖

這裏是我的代碼:

import javax.swing.*; 
import java.awt.event.*; 
public class mouse { 
    private static int x,y; 
    private static draw object = new draw(); 
    public static void main(String[] args){ 
     JFrame frame = new JFrame ("Mouse"); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(400,400); 
     frame.add(object); 
     object.addMouseListener(new AL()); 
    } 
    static class AL extends MouseAdapter{ 
     public void mousePressed(MouseEvent e){ 
     x = e.getX(); 
     y = e.getY(); 
     object.drawing(x, y); 
     } 
     public void mouseDragged(MouseEvent e) { 
     x= e.getX(); 
     y= e.getY(); 
     object.drawing(x, y); 
     } 
    } 
} 

和我已經是添加你的鼠標座標每到一個單獨的列表,只要點擊鼠標時,借鑑基礎上,

import javax.swing.*; 
import java.awt.*; 

public class draw extends JPanel { 
    private static int x,y; 
    public void drawing (int xx, int yy){ 
     x=xx; 
     y=yy; 
     repaint(); 
    } 

    public void paintComponent (Graphics g){ 
     g.setColor(Color.black); 
     g.fillOval(x, y, 10, 10); 
    } 
} 

回答

0

一個想法但是由於您正在使用鼠標拖動,因此您可以使用Path2D.lineTo(x, y)並將e.getX()e.getY()用於x和y座標。在此之後,使用Path2D.moveTo(x, y)確保爲鼠標移動的每個像素添加線路徑(這可以確保每個移動看起來不像一條直線,而更像是一條移動您正在「繪製」的任何方向的線)。此外,一些提示:從

  1. 空隙中mouseMotionAdapter使用時mouseDragged通常工作更好,因爲我的經驗,一般不登記在短短mouseAdapter事件。

  2. 因爲這是一個繪圖程序,所以我個人會設置一個變量,用於將來要使用的圓的大小,如果您實際上正在計劃將其擴大爲更大的東西(例如:g.fillOval(x ,y,brushSize,brushSize))。