Tuesday, December 20, 2011

Creating a Paint Brush Application in java - 1

In this post, I show how to create a Paint Brush application in java swings. In this application if you click and drag the mouse it will paint a line on the window.
Create a class PaintBrush.java extend it from JFrame class. Because a frame represents a window with a title bar and borders. Frame becomes the basis for creating the screens for an application because all the components go into the frame.

To create a frame, we have to create an object to JFrame class in swing.

PaintBrush.java 

import javax.swing.*;
public class PaintBrush extends JFrame
{

      // initializing the frame
 public PaintBrush()
{
     setVisible(true);
     setTitle("Paint Brush");
     setSize(400,400);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
 public static void main(String args[])
{
       PaintBrush pbrush=new PaintBrush();
}
}

If you compile and run the above program it will display a window with 400px width ,400px height and with a title "Paint Brush".







Now create a class MyPanel.java which extends JPanel class.

MyPanel.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyPanel extends JPanel implements MouseMotionListener
{  
    int x1,y1;
    public MyPanel()
    {
// to listen the mouse events (mouse dragging and mouse moving)
    addMouseMotionListener(this);
  
    }
  
    public void paint(Graphics g)
    {

        g.setColor(Color.black);          
        g.fillOval(x1,y1,15,15);
    }

// this method is invoked when we drag the mouse
    public void mouseDragged(MouseEvent me)
    {  
      
        x1=me.getX(); // to save the mouse pointer x-coordinate while dragging.
        y1=me.getY(); // to save the mouse pointer y-coordinate while dragging.
      
        repaint();
    }
    public void mouseMoved(MouseEvent me)
    {

    }
}
Compile and run the above classes and start painting ..




5 comments:

  1. Replies
    1. If you are trying to developing a Paint Brush Application in java... than try this code to get help, may be its useful for you. url--->http://gauravsiwach.blogspot.in/2011/11/paint-brush-program-in-java-applet.html

      Delete
  2. thank you soooo much!
    that helped a lot.

    ReplyDelete
    Replies
    1. If you are trying to developing a Paint Brush Application in java... than try this code to get help, may be its useful for you. url--->http://gauravsiwach.blogspot.in/2011/11/paint-brush-program-in-java-applet.html

      Delete
  3. This comment has been removed by the author.

    ReplyDelete