Tuesday, April 24, 2012

Class Painter: Drawing with Mouse in Java


programmerpro - Class Painter can be used to create small programs that make up the line with the mouse (when the mouse-drag).
Here's his view:




program :

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

public class Painter extends JFrame {
    private int pointCount = 0;
    private Point points[] = new Point[1000];

    public Painter () {
        super ("Program menggambar sederhana");

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

        addMouseMotionListener (
            new MouseMotionAdapter() {
                public void mouseDragged (MouseEvent e) {
                    if (pointCount < points.length) {
                        points[pointCount] = e.getPoint();
                        ++pointCount;
                        repaint();
                    }
                }
            } //end of anonymous class
        ); //end method addMotionListener

        setSize (300,150);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void paint (Graphics g) {
        super.paint(g);
        for (int i = 0; i < points.length && points[i] != null; i++) {
            g.setColor(Color.red);
            g.fillOval (points[i].x, points[i].y, 4,4);
        }
    }

    public static void main (String args[]) {
     Painter test = new Painter();
     test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Related Posts by Categories

No comments:

Post a Comment