Java AWT Graphics draw with mouse

Description

Java AWT Graphics draw with mouse


import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JPanel {
  private final List<Point> points = new ArrayList<>();

  public Main() {
    addMouseMotionListener(new MouseMotionAdapter() 
    {/*from   ww  w  .  j  a v  a2  s .  c o  m*/
      @Override
      public void mouseDragged(MouseEvent event) {
        points.add(event.getPoint());
        repaint(); // repaint JFrame
      }
    });
  }

  // draw ovals in a 5-by-5 at specified locations
  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g); // clears drawing area

    // draw all
    for (Point point : points)
      g.fillOval(point.x, point.y, 5, 5);
  }

  public static void main(String[] args) {
    JFrame application = new JFrame("A simple paint program");

    Main Main = new Main();
    application.add(Main, BorderLayout.CENTER);

    application.add(new JLabel("Drag the mouse to draw"), BorderLayout.SOUTH);

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    application.setSize(400, 200);
    application.setVisible(true);
  }
}



PreviousNext

Related