Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab4.gui;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.util.Observable;
- import java.util.Observer;
- import javax.swing.JPanel;
- import lab4.data.GameGrid;
- /**
- * A panel providing a graphical view of the game board
- */
- public class GamePanel extends JPanel implements Observer{
- private final int UNIT_SIZE = 20;
- private GameGrid grid;
- /**
- * The constructor
- *
- * @param grid The grid that is to be displayed
- */
- public GamePanel(GameGrid grid){
- this.grid = grid;
- grid.addObserver(this);
- Dimension d = new Dimension(grid.getSize()*UNIT_SIZE+1, grid.getSize()*UNIT_SIZE+1);
- this.setMinimumSize(d);
- this.setPreferredSize(d);
- this.setBackground(Color.WHITE);
- }
- /**
- * Returns a grid position given pixel coordinates
- * of the panel
- *
- * @param x the x coordinates
- * @param y the y coordinates
- * @return an integer array containing the [x, y] grid position
- */
- public int[] getGridPosition(int x, int y){
- x = (int)(x / UNIT_SIZE);
- y = (int)(y / UNIT_SIZE);
- return new int[]{x,y};
- }
- public void update(Observable arg0, Object arg1) {
- this.repaint();
- }
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- int size = grid.getSize();
- g.setColor(Color.black);
- for(int i = 0; i < size; i++){
- int x = i * UNIT_SIZE;
- int y = x;
- g.drawRect(x, 0, UNIT_SIZE * size, UNIT_SIZE);
- g.drawRect(0, y, UNIT_SIZE, UNIT_SIZE * size);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement