你有基本的想法。检测鼠标点击,绘制新的形状。
下一步是要知道何时按下shift键并知道最后(或选定)形状是什么,然后才能更新它的位置。
对我来说,最简单的解决方案是以某种方式维护形状和位置信息。在这个例子中,我使用了一个简单的Drawable
类,它不仅结合了位置和形状,还有简单的draw
方法来简化生活。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ShiftShape {
public static void main(String[] args) {
new ShiftShape();
}
public ShiftShape() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private List<Drawable> drawables;
public TestPane() {
drawables = new ArrayList<Drawable>(25);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Drawable drawable = null;
if ((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK) == MouseEvent.SHIFT_DOWN_MASK) {
if (!drawables.isEmpty()) {
drawable = drawables.get(drawables.size() - 1);
}
} else {
drawable = new Drawable();
drawables.add(drawable);
}
if (drawable != null) {
drawable.setLocation(e.getPoint());
repaint();
}
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Drawable drawable : drawables) {
drawable.draw(g2d);
}
g2d.dispose();
}
public class Drawable {
private Point location;
private Shape shape;
public Drawable() {
shape = new Ellipse2D.Float(0, 0, 20, 20);
}
public void setLocation(Point location) {
this.location = location;
}
public Point getLocation() {
return location;
}
public void draw(Graphics2D g2d) {
Point p = getLocation();
int x = p.x - 10;
int y = p.y - 10;
g2d.translate(x, y);
g2d.draw(shape);
g2d.translate(-x, -y);
}
}
}
}
标准图纸就是这样 - 绘图。它立即生成栅格(即将形状定义的路径转换为图形对象)。因此,这些对象作为独立实体“不复存在”(实际上从来不能直接响应UI事件)。您必须独立于图形处理对象布局/图形(和连接) - 然后根据需要绘制布局/图形(在更新所述对象之后)。当然,我确定有这样的库。 – user2246674
您可以查看[此处]引用的示例(http://stackoverflow.com/a/11944233/230513)。 – trashgod
你需要跟踪你想在List WITH POINTS!中绘制的每个对象,并且对于任何移动只需清除(不是整个图形)容器并用新的点重新绘制内容,关于要添加像运动的圆和线接口到src对象,将关联对象移动到,由src移动触发(触发) – 2013-06-30 22:01:52