简体   繁体   English

在Graphics2D类中绘制直线拖放

[英]Drawing a straight line drag and drop in class Graphics2D

How can I draw a straight line on a drag and drop, that there was only one line and moved around? 我如何在拖放中画一条直线,即只有一条线可以移动?

My code: 我的代码:

panelPaint.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    point1 = e.getPoint();
                }
            });
            panelPaint.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    point2 = e.getPoint();

                    g2.draw(new Line2D.Double(point1, point2));

                    panelPaint.repaint();
                }
            });

Current effect: 当前效果:

https://i.stack.imgur.com/tWFCE.png

Looks like you are drawing to a BufferedImage or something. 看起来您正在绘制BufferedImage或其他内容。 You should not be doing painting using a Graphics object in the mouse event. 您不应在鼠标事件中使用Graphics对象进行绘画。

Instead you should be doing custom painting on a panel and override the paintCompnent(...) method. 相反,您应该在面板上进行自定义绘制,并覆盖paintCompnent(...)方法。 Your paintComponent() method should look like: 您的paintComponent()方法应类似于:

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

    // custom painting here
    g.drawLine(...);

}

The first statement will clear the background. 第一条语句将清除背景。 The next statement will draw the line between your starting/ending points. 下一条语句将在起点/终点之间划界线。

Check out Custom Painting Approaches for more information and examples. 查看自定义绘画方法,以获取更多信息和示例。 The example will dynamically draw a Rectangle as you drag the mouse, but the concept is the same for a single line. 该示例将在您拖动鼠标时动态绘制一个Rectangle,但是这一概念对于单行是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM