所以我正在做一个应用程序,我想跟踪添加到屏幕上的形状。到目前为止,我有以下代码,但是当添加一个圆时,它不能被移动/更改。理想情况下,我希望通过按住shift键并单击来移动/高亮显示它。
我也想知道如何才能做到这一点,这样你就可以将一条线从一个圆拖到另一个圆。我不知道我在这里是否使用了错误的工具,但任何帮助都将不胜感激。
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();
}
}发布于 2013-06-29 06:09:13
使用java.awt.geom.*创建形状,使用字段引用它们,然后使用图形对象绘制它们。
例如:
Ellipse2D.Float ellipse=new Ellipse2D.Float(50,50,100,100);
graphics.draw(ellipse);发布于 2013-06-29 06:52:29
1)点击/选择绘制对象见this answer,按下鼠标拖动创建线见here。
2)您不应该覆盖JFrame paint(..)。
相反,将JPanel添加到JFrame并覆盖JPanel的paintComponent(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)文档:
此外,如果您不调用super的实现,则必须遵守opaque属性,即如果此组件是不透明的,则必须使用非不透明颜色完全填充背景。如果您不遵守不透明属性,您很可能会看到可视工件。
3)不要在JFrame上调用setSize,使用正确的LayoutManager和/或覆盖getPreferredSize (通常在绘制到JPanel时这样做,以便它可以适合我们的图形内容),然后在JFrame上调用pack(),然后将其设置为可见。
4)阅读Concurrecny in Swing,特别是Event-Dispatch-Thread。
发布于 2013-06-29 06:46:35
您正在扩展JFrame,因此应该考虑在重写的paint方法的开头调用super.paint(g);。
https://stackoverflow.com/questions/17374322
复制相似问题