Skip to content

Instantly share code, notes, and snippets.

@kyldvs
Created December 7, 2013 22:00
Show Gist options
  • Save kyldvs/7849562 to your computer and use it in GitHub Desktop.
Save kyldvs/7849562 to your computer and use it in GitHub Desktop.
Drawing an image from a 2D array of colors in java
package graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import algorithm.parts.Cell;
import algorithm.parts.State;
public class SimpleDisplay implements Display {
private final int scale = 5;
private final JFrame frame;
private final MyPanel panel;
public SimpleDisplay(State state) {
int n = state.getGrid().length * scale;
int m = state.getGrid()[0].length * scale;
frame = new JFrame("Simulation");
frame.setLayout(new MigLayout("fill"));
frame.setMinimumSize(new Dimension(n, m));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new MyPanel(state);
frame.add(panel, "grow");
}
@Override
public void draw(State state) {
panel.setState(state);
frame.repaint();
}
@SuppressWarnings("serial")
private class MyPanel extends JPanel {
private State state;
private MyPanel(State state) {
this.state = state;
}
public void setState(State state) {
this.state = state;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Cell[][] grid = state.getGrid();
for (int i = 0; i < grid.length; i++)
{
for (int j = 0; j < grid[0].length; j++)
{
g.setColor(new Color(grid[i][j].rgb));
g.fillRect(i * scale, j * scale, scale, scale);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment