2013-06-28 71 views
4

所以我正在製作一個應用程序,我想跟蹤添加到屏幕上的形狀。到目前爲止,我有以下代碼,但添加一個圓時不能移動/更改。理想情況下,我想要按住shift鍵點擊它來移動/突出顯示它。Java圖形 - 保持跟蹤形狀

我也想知道我怎樣才能讓它可以從一個圓圈拖到另一個圓圈。我不知道我是否在這裏使用了錯誤的工具來完成這項工作,但是我會感激任何幫助。

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

public class MappingApp extends JFrame implements MouseListener { 

    private int x=50; // leftmost pixel in circle has this x-coordinate 
    private int y=50; // topmost pixel in circle has this y-coordinate 

    public MappingApp() { 
    setSize(800,800); 
    setLocation(100,100); 
    addMouseListener(this); 
    setVisible(true); 
    } 

    // paint is called automatically when program begins, when window is 
    // refreshed and when repaint() is invoked 
    public void paint(Graphics g) { 
    g.setColor(Color.yellow); 
    g.fillOval(x,y,100,100); 

} 

    // The next 4 methods must be defined, but you won't use them. 
    public void mouseReleased(MouseEvent e) { } 
    public void mouseEntered(MouseEvent e) { } 
    public void mouseExited(MouseEvent e) { } 
    public void mousePressed(MouseEvent e) { } 

    public void mouseClicked(MouseEvent e) { 
    x = e.getX(); // x-coordinate of the mouse click 
    y = e.getY(); // y-coordinate of the mouse click 
    repaint(); //calls paint() 
    } 

    public static void main(String argv[]) { 
    DrawCircle c = new DrawCircle(); 
    } 
} 

回答

5

使用java.awt.geom。*創建形狀,使用字段來引用它們,然後使用圖形對象來繪製它們。

爲如:

Ellipse2D.Float ellipse=new Ellipse2D.Float(50,50,100,100); 

graphics.draw(ellipse); 
+0

graphics.draw(ellipse);給我一個錯誤... – Tim

+0

圖形是僞的。我指的是你使用的任何圖形對象。您使用'g'作爲參考的例子。嘗試使用g.draw() – Nikki

+0

+1來繪製Shapes。但是,Graphics類不知道如何繪製形狀。你需要使用'Graphics2D'類。你也應該使用'fill()'方法。 draw()方法只是繪製Shape的輪廓。有關更多信息,請參見[使用形狀](http://tips4java.wordpress.com/2013/05/13/playing-with-shapes/)。 – camickr

0

你是在擴展JFrame的,所以你應該考慮調用super.paint(G);在重寫的paint方法的開始處。

+1

OP甚至應該重寫'JFrame'的'paint' .. –

4

1)請參閱this答案點擊/選擇一個繪製的對象和here通過按下,並拖動鼠標創建線。

2)你不應該凌駕於JFramepaint(..)

而是添加JPanelJFrame和覆蓋的JPanelpaintComponent(Graphics g)不忘打電話super.paintComponent(g);作爲覆蓋方法第一次調用:

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    g.setColor(Color.yellow); 
    g.fillOval(x,y,100,100); 

} 

paintComponent(Graphics g)

文檔:

此外,如果你這樣做不是invoker super的實現,你必須承認 的不透明屬性,也就是說如果這個組件是不透明的,你必須 comp以不透明的顏色填充背景。如果你不尊重不透明的財產,你可能會看到視覺文物。

3)不要叫setSizeJFrame使用正確LayoutManager和/或覆蓋getPreferredSize(繪圖JPanel時,因此它可能適合我們的圖形內容),比它設置可見之前JFrame致電pack()通常完成。

4)請仔細閱讀Concurrecny in Swing,特別是Event-Dispatch-Thread

+3

我只注意到你通過了20K!恭喜,這是當之無愧的。 :) –

+2

+1呵呵謝謝你我覺得我可以說我知道一點關於Swing :)! –