package graphics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; /** * That's the interface implemented by EasyGraphics. * It's the minimal set of methods needed. */ interface GraphicsInterface { public void repaint(); // (re)paints the image public void set(int x, int y, int rgb); // sets a pixel public int get(int x, int y); // reads a pixel } /** * Helper Class. * It extends JPlanel to overwrite paintComponent. */ class DrawingPanel extends JPanel { private static final long serialVersionUID = 1L; public final BufferedImage bufferedImage; public final int width; public final int height; public DrawingPanel(int w, int h) { width = w; height = h; // Create image for double buffering bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2dComponent = (Graphics2D) g; g2dComponent.drawImage(bufferedImage, null, 0, 0); } } /** * Wrapper class for Java graphics. * The main idea is to simplify Java graphics but still offer all the functionality needed. */ public class EasyGraphics implements GraphicsInterface { public JFrame frame; public DrawingPanel drawing; public EasyGraphics(String title, int width, int height) { frame = new JFrame(); drawing = new DrawingPanel(width, height); frame.add(drawing); frame.setSize(width, height); frame.setTitle(title); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public EasyGraphics() { this("Easy Graphics", 640, 480); } public void repaint() { drawing.repaint(); } public void set(int x, int y, int rgb) { drawing.bufferedImage.setRGB(x, y, rgb); } public int get(int x, int y) { return drawing.bufferedImage.getRGB(x, y); } }