Drawing lines with mouse on canvas : Java awt

允我心安 提交于 2019-11-30 20:37:46
Mikle Garin

Here is a simple example of such "painting":

public static void main ( String[] args )
{
    JFrame paint = new JFrame ();

    paint.add ( new JComponent ()
    {
        private List<Shape> shapes = new ArrayList<Shape> ();
        private Shape currentShape = null;

        {
        MouseAdapter mouseAdapter = new MouseAdapter ()
        {
            public void mousePressed ( MouseEvent e )
            {
            currentShape = new Line2D.Double ( e.getPoint (), e.getPoint () );
            shapes.add ( currentShape );
            repaint ();
            }

            public void mouseDragged ( MouseEvent e )
            {
            Line2D shape = ( Line2D ) currentShape;
            shape.setLine ( shape.getP1 (), e.getPoint () );
            repaint ();
            }

            public void mouseReleased ( MouseEvent e )
            {
            currentShape = null;
            repaint ();
            }
        };
        addMouseListener ( mouseAdapter );
        addMouseMotionListener ( mouseAdapter );
        }

        protected void paintComponent ( Graphics g )
        {
        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setPaint ( Color.BLACK );
        for ( Shape shape : shapes )
        {
            g2d.draw ( shape );
        }
        }
    } );

    paint.setSize ( 500, 500 );
    paint.setLocationRelativeTo ( null );
    paint.setVisible ( true );
}

it will remember all of the drawn shapes and with a small effort you can extend it to draw any other shapes you like.

Make use of Line2D object in the AWT package and do the following steps:

  1. Create mouse (X,Y) values for first and second clicks
  2. Create a boolean variable to check if the click is the first or the second
  3. Make a List container to contain your Line2D objects
  4. Draw them in your Can object
  5. Assign the before and after (X,Y) values through the mouse listener's event

The step number 5 could be achieved through:

  1. e.getX()
  2. e.getY()

Where e is the mouse event and could be accesed through the parameter of the mouse listener method.

You should use the Line2D object in the awt package, create x and y values for the first click and the second click, and a boolean determining whether it's the first or second click. Then make an ArrayList of Line2D and draw them in your Can object. So then you can assign the before and after x and y values with your event in the mouse listener by using MouseEvent.getX() and getY().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!