1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
package ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
import laboratory.Simulation;
/**
* The simulation panel
*/
@SuppressWarnings("serial")
public
class SimulationPanel extends JPanel {
/** The dimension */
private final Dimension dimension ;
/** The size of an agent on the panel */
private final int pSize = 5;
/** The current simulation */
private Simulation simulation ;
/** The x margin */
private final int xMargin = 0;
/** The y margin */
private final int yMargin = 0;
/**
* Creates a new simulation panel.
* @param simulation the current simulation
*/
public SimulationPanel(Simulation simulation) {
this.simulation = simulation;
dimension = simulation.getDimension();
int gray = 227;
this.setBackground(new Color(gray, gray, gray));
}
/**
* Draw a rectangle of the given color at the given location.
* @param x the <i>x</i> coordinate of the rectangle
* @param y the <i>y</i> coordinate of the rectangle
* @param color the color to fill the rectangle
*/
private void draw(int x, int y, Color color) {
Graphics g = this.getGraphics();
if (color == null) color = Color.gray ;
g.setColor(color);
g.fillRect(xMargin+x*pSize, yMargin+y*pSize, pSize-1, pSize-1);
}
/**
* Paint the content of the simulation panel.
*/
public void paintComponent(Graphics g) {
if (this.isShowing()) {
super.paintComponent(g); // Do whatever usually is done.
g.setColor(Color.gray);
g.fillRect(xMargin-1, yMargin-1, dimension.width*pSize+1, dimension.height*pSize+1);
for (int x=0; x<dimension.width; x++)
for (int y=0; y<dimension.height; y++)
repaint(x,y);
}
}
/**
* Repaint the given place according to the color of the agent present at this place.
* @param x the <i>x</i> coordinate of the place to repaint
* @param y the <i>y</i> coordinate of the place to repaint
*/
public void repaint(int x, int y) {
if (this.isShowing())
draw(x,y, simulation.getColor(x,y));
}
/**
* Sets the simulation.
* @param simulation the simulation to set
*/
public void setSimulation(Simulation simulation) {
this.simulation = simulation;
paintComponent(this.getGraphics());
}
} |
Partager