Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package paint;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.Image;
- import java.awt.RenderingHints;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import java.awt.event.MouseMotionAdapter;
- import javax.naming.AuthenticationNotSupportedException;
- import javax.swing.JComponent;
- public class Sketch extends JComponent {
- //image we are going to draw
- private Image image ;
- // used to draw on
- public Graphics2D graphic ;
- //cursor
- private int OldX , OldY , CurrentX , CurrentY;
- public Sketch (){
- setDoubleBuffered(false);
- addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- // save coord x , y when mouse is pressed
- OldX=e.getX();
- OldY=e.getY();
- }
- });
- addMouseMotionListener(new MouseMotionAdapter() {
- @Override
- public void mouseDragged(MouseEvent e) {
- // save coord x , y when mouse is moving .. gets the last point
- CurrentX=e.getX();
- CurrentY=e.getY();
- if (graphic !=null){
- graphic.drawLine(OldX , OldY , CurrentX , CurrentY);
- repaint();
- OldX = CurrentX;
- OldY = CurrentY;
- }
- }
- });
- }
- protected void paintComponent (Graphics e ) {
- if (image == null ){
- image = createImage(getSize().width, getSize().height);
- //add the line drawn to the graphic
- graphic = (Graphics2D) image.getGraphics();
- //remove sharpness
- graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- clear();
- }
- e.drawImage(image, 0, 0, null);
- }
- public void clear(){
- graphic.setPaint(Color.white );
- //turn drawing area to white
- graphic.fillRect(0, 0, getSize().width, getSize().height);
- graphic.setPaint(Color.black );
- repaint();
- }
- public void red(){
- graphic.setPaint(Color.red);
- System.out.println("hey");
- repaint();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement