TrodelHD

Untitled

Mar 11th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. package Spiel;
  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.swing.JComponent;
  13.  
  14. /**
  15. * Component for drawing !
  16. *
  17. * @author sylsau
  18. *
  19. */
  20. public class DrawArea extends JComponent {
  21.  
  22. // Image in which we're going to draw
  23. private Image image;
  24. // Graphics2D object ==> used to draw on
  25. private Graphics2D g2;
  26. // Mouse coordinates
  27. private int currentX, currentY, oldX, oldY;
  28.  
  29. public DrawArea() {
  30. setDoubleBuffered(false);
  31. addMouseListener(new MouseAdapter() {
  32. public void mousePressed(MouseEvent e) {
  33. // save coord x,y when mouse is pressed
  34. oldX = e.getX();
  35. oldY = e.getY();
  36. }
  37. });
  38.  
  39. addMouseMotionListener(new MouseMotionAdapter() {
  40. public void mouseDragged(MouseEvent e) {
  41. // coord x,y when drag mouse
  42. currentX = e.getX();
  43. currentY = e.getY();
  44.  
  45. if (g2 != null) {
  46. // draw line if g2 context not null
  47. g2.drawLine(oldX, oldY, currentX, currentY);
  48. // refresh draw area to repaint
  49. repaint();
  50. // store current coords x,y as olds x,y
  51. oldX = currentX;
  52. oldY = currentY;
  53. }
  54. }
  55. });
  56. }
  57.  
  58. protected void paintComponent(Graphics g) {
  59. if (image == null) {
  60. // image to draw null ==> we create
  61. image = createImage(getSize().width, getSize().height);
  62. g2 = (Graphics2D) image.getGraphics();
  63. // enable antialiasing
  64. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  65. // clear draw area
  66. clear();
  67. }
  68.  
  69. g.drawImage(image, 0, 0, null);
  70. }
  71.  
  72. // now we create exposed methods
  73. public void clear() {
  74. g2.setPaint(Color.white);
  75. // draw white on entire draw area to clear
  76. g2.fillRect(0, 0, getSize().width, getSize().height);
  77. g2.setPaint(Color.black);
  78. repaint();
  79. }
  80.  
  81. public void red() {
  82. // apply red color on g2 context
  83. g2.setPaint(Color.red);
  84. }
  85.  
  86. public void black() {
  87. g2.setPaint(Color.black);
  88. }
  89.  
  90. public void magenta() {
  91. g2.setPaint(Color.magenta);
  92. }
  93.  
  94. public void green() {
  95. g2.setPaint(Color.green);
  96. }
  97.  
  98. public void blue() {
  99. g2.setPaint(Color.blue);
  100. }
  101.  
  102. }
Add Comment
Please, Sign In to add comment