LightCanvasJPanel.java 1.77 KB
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

public class LightCanvasJPanel extends JPanel {
	public static final double[][] DEFAULT_LIGHT_COORDS = new double[][] {
		{0, 0}  , {0.2, 0}  , {0.4, 0}  , {0.6  , 0}, {0.8, 0}  , {1, 0}  ,
		{0, 0.2}, {0.2, 0.2}, {0.4, 0.2}, {0.6, 0.2}, {0.8, 0.2}, {1, 0.2},
		{0, 0.4}, {0.2, 0.4}, {0.4, 0.4}, {0.6, 0.4}, {0.8, 0.4}, {1, 0.4},
		{0, 0.6}, {0.2, 0.6}, {0.4, 0.6}, {0.6, 0.6}, {0.8, 0.6}, {1, 0.6},
		{0, 0.8}, {0.2, 0.8}, {0.4, 0.8}, {0.6, 0.8}, {0.8, 0.8}, {1, 0.8},
		{0, 1}  , {0.2, 1}  , {0.4, 1}  , {0.6, 1}  , {0.8, 1}  , {1, 1}  ,
	};
	
	private static final long serialVersionUID = 1L;
	private static final int WIDTH = 320; // = 300 + padding * 2
	private static final int HEIGHT = 220; // = 200 + padding * 2
	private static final int LIGHT_RADIUS = 4;
	private static final int PADDING = 10;
	private double[][] lightsCoords;
	
	/**
	 * @param lightCoords : double[LightID][X = 0, Y = 1] = coordinates as a percentage [0, 1]
	 */
	public LightCanvasJPanel() {this(DEFAULT_LIGHT_COORDS);}
	public LightCanvasJPanel(double[][] lightsCoords) {
		this.lightsCoords = lightsCoords;
		setPreferredSize(new Dimension(WIDTH, HEIGHT));
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		// background
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);
		
		// lights
		if(lightsCoords == null) return;
		g.setColor(Color.BLACK);
		for(double[] light : lightsCoords) {
			if(light.length != 2)
				throw new MalformedCoordinates();
			int centerX = (int) (light[0] * (WIDTH - PADDING * 2)) + PADDING;
			int centerY = (int) (light[1] * (HEIGHT - PADDING * 2)) + PADDING;
			
			g.fillOval(centerX - LIGHT_RADIUS, centerY - LIGHT_RADIUS, LIGHT_RADIUS * 2, LIGHT_RADIUS * 2);
		}
	}
}