当鼠标移动的Java画线 [英] java draw line as the mouse is moved

查看:98
本文介绍了当鼠标移动的Java画线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个功能添加到我的应用程序,其允许用户通过点击鼠标在开始位置和结束位置释放它画出一条直线。该行应作为移动鼠标移动,直到它终于发布;同样,由线可以使用Microsoft画图应用程序绘制的方式。

I would like to add a feature to my application which allows the user to draw a straight line by clicking the mouse at the start location and releasing it at the end location. The line should move as the mouse moves until it is finally released; similar to the way that a line can be drawn using the Microsoft Paint application.

使线路重新绘制,因为它没有移动重绘可能已在该矩形区域绘制其他东西如何实现这一点?

How can implement this so that the line is repainted as it moves without repainting other things that may already be drawn in that rectangular area?

推荐答案

试试这个......在屏幕上绘制一条红线把鼠标移动(拖)。

Try this...Draw a red line on the screen as the mouse is moved (dragged).

public static void main(String args[]) throws Exception {
    JFrame f = new JFrame("Draw a Red Line");
    f.setSize(300, 300);
    f.setLocation(300, 300);
    f.setResizable(false);
    JPanel p = new JPanel() {
        Point pointStart = null;
        Point pointEnd   = null;
        {
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    pointStart = e.getPoint();
                }

                public void mouseReleased(MouseEvent e) {
                    pointStart = null;
                }
            });
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseMoved(MouseEvent e) {
                    pointEnd = e.getPoint();
                }

                public void mouseDragged(MouseEvent e) {
                    pointEnd = e.getPoint();
                    repaint();
                }
            });
        }
        public void paint(Graphics g) {
            super.paint(g);
            if (pointStart != null) {
                g.setColor(Color.RED);
                g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
            }
        }
    };
    f.add(p);
    f.setVisible(true); 
}

这篇关于当鼠标移动的Java画线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆