2015-09-26 98 views
-5

目前我正在用Java鼠標點擊繪製Java程序。就像Photoshop或在微軟繪畫應用程序一樣。 我知道通過設置X軸和Y軸的邊界很容易繪製正方形。但是如何用鼠標點擊製作像非洲地圖那樣的複雜形狀的方法?有沒有爲此設置邊界? 任何人都可以給我提示嗎?謝謝! map of Africa example如何在Java中製作地圖繪製軟件

+3

這不是代碼提供網站。如果你有一些確切的問題,我們將幫助你分享。請參觀遊覽。 – Panther

+1

找出你如何繪製一條線 – MadProgrammer

回答

-2

繪畫是可能的與java Graphics。嘗試遵循簡單的代碼。

public class PaintCanves extends JPanel { 

    private int oldX; 
    private int oldY; 

    public PaintCanves() { 
     draw(); 
    } 

    private void draw() { 
     addMouseListener(new MouseAdapter() { 
      @Override 
      public void mousePressed(MouseEvent e) { 
       oldX = e.getX(); 
       oldY = e.getY(); 
      } 
     }); 

     addMouseMotionListener(new MouseMotionAdapter() { 
      @Override 
      public void mouseDragged(MouseEvent e) { 
       getGraphics().drawLine(oldX, oldY, e.getX(), e.getY()); 
       oldX = e.getX(); 
       oldY = e.getY(); 

      } 
     }); 
    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setContentPane(new PaintCanves()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(500, 500); 
     frame.setVisible(true); 
    } 
} 

這是我的測試結果。

enter image description here

注:

它調用repaint()面板時清除已繪製數據。需要使用諸如將繪畫點添加到Collection之類的技術來保持繪畫點的安全。

+0

....並且請告訴我當你最小化然後恢復你的GUI時會發生什麼?你的繪畫是否持續?請不要給出誤導性的建議,比如像上面那樣使用'getGraphics()'。在Swing中繪圖是被動的,應該在paintComponent方法中完成,就像下面詳細解釋的繪畫教程一樣:[Lesson:Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html)和[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html) –

+0

面板重新繪製。所以它會丟失已經繪製的所有數據。我只是試圖向你展示如何使用java繪製鼠標。 –

+0

是的,你展示了原來的海報**錯誤**的方式來做到這一點! –