Advertisement
Guest User

Sketch Class

a guest
Oct 25th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. package paint;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Graphics;
  5. import java.awt.Graphics2D;
  6. import java.awt.Image;
  7. import java.awt.RenderingHints;
  8. import java.awt.event.MouseAdapter;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseMotionAdapter;
  11.  
  12. import javax.naming.AuthenticationNotSupportedException;
  13. import javax.swing.JComponent;
  14.  
  15. public class Sketch extends JComponent {
  16.  
  17.  
  18. //image we are going to draw
  19. private Image image ;
  20. // used to draw on
  21. public Graphics2D graphic ;
  22. //cursor
  23. private int OldX , OldY , CurrentX , CurrentY;
  24.  
  25. public Sketch (){
  26. setDoubleBuffered(false);
  27.  
  28. addMouseListener(new MouseAdapter() {
  29.  
  30. @Override
  31. public void mousePressed(MouseEvent e) {
  32. // save coord x , y when mouse is pressed
  33.  
  34. OldX=e.getX();
  35. OldY=e.getY();
  36. }
  37.  
  38. });
  39.  
  40. addMouseMotionListener(new MouseMotionAdapter() {
  41.  
  42. @Override
  43. public void mouseDragged(MouseEvent e) {
  44. // save coord x , y when mouse is moving .. gets the last point
  45. CurrentX=e.getX();
  46. CurrentY=e.getY();
  47.  
  48. if (graphic !=null){
  49. graphic.drawLine(OldX , OldY , CurrentX , CurrentY);
  50. repaint();
  51. OldX = CurrentX;
  52. OldY = CurrentY;
  53. }
  54. }
  55.  
  56. });
  57. }
  58. protected void paintComponent (Graphics e ) {
  59. if (image == null ){
  60. image = createImage(getSize().width, getSize().height);
  61. //add the line drawn to the graphic
  62. graphic = (Graphics2D) image.getGraphics();
  63. //remove sharpness
  64. graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  65. clear();
  66. }
  67. e.drawImage(image, 0, 0, null);
  68.  
  69.  
  70. }
  71. public void clear(){
  72.  
  73. graphic.setPaint(Color.white );
  74. //turn drawing area to white
  75. graphic.fillRect(0, 0, getSize().width, getSize().height);
  76. graphic.setPaint(Color.black );
  77. repaint();
  78.  
  79. }
  80. public void red(){
  81. graphic.setPaint(Color.red);
  82. System.out.println("hey");
  83.  
  84. repaint();
  85. }
  86.  
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement