Advertisement
Guest User

Untitled

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