0 Replies - 350 Views - Last Post: 21 July 2009 - 10:47 PM

#1 jyth   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 29-June 09

A Basic Graphics Window

Posted 21 July 2009 - 10:47 PM

Description: 1. Create an instance of the class with the desired dimensions, what have you 2. Get the graphics object with getGraphics() 3. Draw using the graphics object (it has many different methods) 4. Render the frame with renderBuffer() Repeat 2/3/4 Since when I began looking into graphics in java I had a tough time finding my way around, this is a basic class for creating a window to draw on I use for my asteroids game
package jaglibrary.window;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;

 * A basic window for graphics
 * @author Justin
public class BasicWindow extends Canvas {

    private final JFrame frame;
    private final BufferStrategy bufferStrategy;
    private Graphics2D graphics;

     * Initializes a window
     * Creates a JFrame to contain the class in (an extension of canvas)
    public BasicWindow(String window_name, Dimension dimensions, int buffer_strategies) {
        // Size of the window
        // MUST be called or else java awt or something calls repaint, bad things happen
        frame = new JFrame();
        // Again..
        // Size again.. I needed to add this because of a small gap between the window border and canvas border
        // Allows usage of alt+tab, etc
        // Adds the canvas to the frame
        // Makes the frame conform to the objects contained within it, namely the canvas
        // Prevents resizing, as this can cause some problems which I havn't bothered to look in to
        // Makes the frame visable
        // Creates a offscreen buffer to be drawn on then rendered to the screen to prevent flickering
        bufferStrategy = getBufferStrategy();
        graphics = (Graphics2D) bufferStrategy.getDrawGraphics();

     * Renders the offscreen buffer
     * Call after all drawing has been done for the current frame
    public void renderBuffer() {
        // Destroys the graphics object used for drawing
        // Shows the frame
        // Creates a new graphics object
        graphics = (Graphics2D) bufferStrategy.getDrawGraphics();

     * Call this method to get the graphics object for drawing
     * @return
    public Graphics2D getGraphics() {
        return graphics;

Is This A Good Question/Topic? 0
  • +

Page 1 of 1