Drawing lines with mouse on canvas : Java awt

后端 未结 3 1408
难免孤独
难免孤独 2021-01-05 05:35

The attempt is to enable drawing of figures(a line for now) with mouse on the awt canvas . Iam trying out java graphics for the first time . So not sure how to go about it .

3条回答
  •  囚心锁ツ
    2021-01-05 06:29

    Here is a simple example of such "painting":

    public static void main ( String[] args )
    {
        JFrame paint = new JFrame ();
    
        paint.add ( new JComponent ()
        {
            private List shapes = new ArrayList ();
            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.

提交回复
热议问题