Translate

Wednesday, August 1, 2012

Awesome Paint Brush



Well, this happens to me accidentally while I  was teaching a set of my kiddies who were indeed interested in making computer games about how to do kinda’ simulation using a computer programming language (java). On the other hand I too wanted them to show kind of multiple inheritance in action.  As you see in the code below the mistake was incredible. Miraculously I have written down a piece of code to simulate a paint brush. The code is very original and indeed may have some hidden professional mistakes. I want let em as they are and some body down who read this blog is expected to correct this code for professional mistakes. 



Picture :  An awesome art from an awesome tool


If you run the code below try whether you could draw the above paint :D.


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Pinsal extends JPanel implements
 MouseMotionListener {
  private int X, Y;
  private Image image1;
  private Image image2;

 
public static void main(String[] args) {
  JFrame frame = new JFrame();
  frame.getContentPane().add(new Pinsal());
  frame.setSize(500, 300);
  frame.show();
  }
  public Pinsal() {
  addMouseMotionListener(this);
  setVisible(true);
  }
  @Override
  public void mouseMoved(MouseEvent event) {
                  // implements MouseMotionListner.mouseMoved
  X = (int) event.getPoint().getX();
  Y = (int) event.getPoint().getY();
  repaint();
  }
  @Override
  public void mouseDragged(MouseEvent event) {
        // implements MouseMotionListner.mouseDragged
  mouseMoved(event);
  }
  @Override
  public void update(Graphics graphics) {
        // javax.swing.Jcomponent.update
  paint(graphics);
  }
  @Override
  public void paint(Graphics g) {
        // javax.swing.Jcomponent.paint
  Dimension dim = getSize();
  draw();
  Graphics graphics1 = image1.getGraphics();
  Graphics graphics2 = image2.getGraphics();                 
  graphics1.setColor(getBackground());
  graphics1.fillRect(0, 0, dim.width, dim.height);
  //colorScreen(image1.getGraphics());
  colorScreen(image2.getGraphics());
  //g.drawImage(image1, 0, 0, null);
  g.drawImage(image2, 0, 0, null);
  }                                                   
  private void draw() {
  Dimension dim = getSize();
  if (image1 == null || image1.getWidth(null) != dim.width
  || image1.getHeight(null) != dim.height) {
  image1 = createImage(dim.width, dim.height);
  }
  if (image2 == null || image2.getWidth(null) != dim.width
              || image2.getHeight(null) != dim.height) {
              image2 = createImage(dim.width, dim.height);
              }
  }
  public void colorScreen(Graphics g) {
  int size = 15;
  g.setColor(Color.CYAN);
  g.fillOval(X - size  / 2, Y - size  / 2, size , size );
  }
}

No comments: