Creating a Simple Paint Program in Java

Introduction In this tutorial, a simple Paint program is created, which enables us to draw anything to screen. It's a basic program to understand the logic behind creating a paint program. Here main concept is implementing MouseMotionListener which handles mouse events. Whenever mouse is dragged a mouse event is sent to Java which finds the event listener in the program in order to take any action. We need to implement only mouseDragged() of many functions of MouseMotionListener class to draw to the Panel. For that we will use Adapter class which adds default implementation for all other functions and we can overload the function we want. Step 1: In order to create stand alone application we require to extend JFrame class. To get x and y positions, where a mouse was dragged for drawing something, two variables x and y are used and initialized to -10. Step 2: Create a label with text "Drag the mouse to draw" and adding it to the bottom of frame using BorderLayout as follows. getContentpane() method is used to get current pane where we can add different components such as label, button, text area, etc.
  1. getContentPane().add(
  2. new Label( "Drag the mouse to draw" ),BorderLayout.SOUTH );
Next we add MouseMotionListener which handles mouse events and mouse drag events can be captured. mouseDragged() method of MouseMotionListner class is overloaded and x and y position where a mouse was dragged are obtained and stored into x and y variables. All the mouseMotionListener's method take MouseEvent type argument which saves information about particular mouse event. Every time mouse is dragged listener's mouseDragged() method is called.In that method repaint() is used which calls paint() method to draw at dragged position.
  1. addMouseMotionListener(
  2. // inner class
  3. // store drag coordinates and repaint
  4. public void mouseDragged( MouseEvent event )
  5. {
  6. x = event.getX();
  7. y = event.getY();
  8. repaint();
  9. }
  10. }
  11. // end inner class
  12. ); // end call to addMouseMotionListener
setSize(400,400) method sets the size of the frame as 400 by 400 pixel. setVisible( true ); method makes sure that frame is visible. Step 3: Finally paint() method is used to draw on the screen. It fills an oval at x and y position. The oval's width and height is set 4 pixel. It means it draw a point at the x and y position.
  1. public void paint( Graphics g )
  2. {
  3.  
  4. g.fillOval( x, y, 4, 4 );
  5. }
Step 4: WindowListener is added to frame in order to close the application properly. This program can be expanded to add more functionality as a real paint program.

Add new comment