Paint & using Mouse in Java

/** this simple program allows user to draw by click & drag with the mouse. The example contains “Main.java” and “draw.java” classes. The “select paint” method in “draw.java” can be used to add new paint style, e.g, different colors. Any queries, feel free to ask…

By Devansh Ramen

*/

// Main.java

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
public class Main {

public static void main(String[] args) {
JFrame window = new JFrame(“Clipping”);
draw content = new draw();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocation(100,75);
window.setSize(500,500);
window.setVisible(true);
}
}

———————————————————————————————————————————–

//draw.java

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JPanel;
//MouseListener: interface containing methods required to ‘listen’ to mouse events
public class draw extends JPanel implements MouseListener, MouseMotionListener {

private int prevX, prevY;
private Graphics paint;
private Polygon triangle= new Polygon();
private String drawtype;

public draw() {
setBackground(Color.WHITE);
addMouseListener(this);
addMouseMotionListener(this);
}

private void selectpaint() {
paint = getGraphics();
paint.setColor(Color.BLACK);
drawtype = “line”;
// to choose polygon to draw
}

public void mousePressed(MouseEvent evt) {
int x = evt.getX(); // capture start position
int y = evt.getY();
prevX = x; //set previous same position at first
prevY = y;
selectpaint();
}

public void mouseReleased(MouseEvent evt) {
paint.dispose();
paint = null;
}

public void line(MouseEvent evt){
int x = evt.getX(); // capture new x coordinate
int y = evt.getY(); // capture new y coordinate
paint.drawLine(prevX, prevY, x, y);
prevX = x;
prevY = y;
}

public void mouseDragged(MouseEvent evt) {
if (drawtype== “line”){
line(evt);
}

}

public void mouseMoved(MouseEvent evt) { } //mouse moves but no button pressed
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }

}

Please Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s