2013-06-28 73 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 :)! –