4

所以我正在制作一个应用程序,我想跟踪添加到屏幕上的形状。到目前为止,我有以下代码,但是当添加一个圆圈时,它无法移动/更改。理想情况下,我想要像 shift-click 这样的东西来移动它/突出显示它。

我也想知道我怎样才能做到这一点,以便您可以将一条线从一个圆圈拖到另一个圆圈。我不知道我是否在这里使用了错误的工具来完成这项工作,但我们将不胜感激。

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

3 回答 3

5

使用 java.awt.geom.* 创建形状,使用字段来引用它们,然后使用图形对象来绘制它们。

例如:

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

graphics.draw(ellipse);
于 2013-06-28T22:09:12.970 回答
4

1)请参阅答案以单击/选择绘制的对象,并在此处通过按下和拖动鼠标创建线条。

2)你不应该压倒一切JFrame paint(..)

而是添加JPanelJFrame覆盖不要忘记在覆盖方法paintComponent(Graphics g)中作为第一个调用调用:JPanelsuper.paintComponent(g);

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

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

}

根据paintComponent(Graphics g)文档:

此外,如果你没有调用 super 的实现,你必须遵守 opaque 属性,也就是说,如果这个组件是不透明的,你必须用不透明的颜色完全填充背景。如果您不尊重 opaque 属性,您可能会看到视觉伪影。

3)不要调用setSize使用JFrame正确LayoutManager和/或覆盖getPreferredSize(通常在绘制时完成,JPanel因此它可能适合我们的图形内容),而不是pack()JFrame设置它可见之前调用。

4) 阅读Swing 中的 Concurrecny特别是Event-Dispatch-Thread

于 2013-06-28T22:52:28.567 回答
0

您正在扩展 JFrame,因此您应该考虑调用 super.paint(g); 在覆盖的绘制方法的开头。

于 2013-06-28T22:46:34.927 回答