Advertisement
Guest User

Untitled

a guest
Feb 20th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. package lab4.gui;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Dimension;
  5. import java.awt.Graphics;
  6. import java.awt.Graphics2D;
  7. import java.util.Observable;
  8. import java.util.Observer;
  9.  
  10. import javax.swing.JPanel;
  11.  
  12. import lab4.data.GameGrid;
  13.  
  14. /**
  15. * A panel providing a graphical view of the game board
  16. */
  17.  
  18. public class GamePanel extends JPanel implements Observer{
  19.  
  20. private final int UNIT_SIZE = 20;
  21. private GameGrid grid;
  22.  
  23. /**
  24. * The constructor
  25. *
  26. * @param grid The grid that is to be displayed
  27. */
  28. public GamePanel(GameGrid grid){
  29. this.grid = grid;
  30. grid.addObserver(this);
  31. Dimension d = new Dimension(grid.getSize()*UNIT_SIZE+1, grid.getSize()*UNIT_SIZE+1);
  32. this.setMinimumSize(d);
  33. this.setPreferredSize(d);
  34. this.setBackground(Color.WHITE);
  35. }
  36.  
  37. /**
  38. * Returns a grid position given pixel coordinates
  39. * of the panel
  40. *
  41. * @param x the x coordinates
  42. * @param y the y coordinates
  43. * @return an integer array containing the [x, y] grid position
  44. */
  45. public int[] getGridPosition(int x, int y){
  46. x = (int)(x / UNIT_SIZE);
  47. y = (int)(y / UNIT_SIZE);
  48. return new int[]{x,y};
  49. }
  50.  
  51. public void update(Observable arg0, Object arg1) {
  52. this.repaint();
  53. }
  54.  
  55. public void paintComponent(Graphics g){
  56. super.paintComponent(g);
  57.  
  58. int size = grid.getSize();
  59. g.setColor(Color.black);
  60. for(int i = 0; i < size; i++){
  61. int x = i * UNIT_SIZE;
  62. int y = x;
  63. g.drawRect(x, 0, UNIT_SIZE * size, UNIT_SIZE);
  64. g.drawRect(0, y, UNIT_SIZE, UNIT_SIZE * size);
  65.  
  66. }
  67.  
  68. }
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement