Question

My friend has make me a simple JFrame, and I am meant to work on it and develop it. I have encountered a problem within the first 30 mins of having it: it's not drawing the graphics!!

Here is the code that draws the graphics, and the code from the class that brings up the JFrame.

Thanks in advance.

GameCanvas.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.LinkedList;

/**
*
* @author Kris
*/
public class GameCanvas extends Canvas{
Player p;
LinkedList<Stalker> s = new LinkedList<>();

public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    p.paintItAll(g2d);
    for(int i = 0; i < s.size(); i++) {
        s.get(i).paintItAll(g2d);
    }
}

public GameCanvas() {
    initComponents();
    repaint();
}

public void initComponents() {
    p = new Player(new Point(50,50));
    s.add(new Stalker(new Point(50,100)));
}

public Point getPlayerPos() {
    return p.getPos();
}
}





MainWindow.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
*
* @author Kris
*/
public class MainWindow extends JFrame{
static Toolkit tk = Toolkit.getDefaultToolkit();
static int xSize = ((int) tk.getScreenSize().getWidth());
static int ySize = ((int) tk.getScreenSize().getHeight());
/**
 * @param args the command line arguments
 */
public MainWindow() {
    super("STALKER!!!!!!!!!!");
    GameCanvas canvas = new GameCanvas();
    add(canvas, BorderLayout.CENTER);
    setSize(xSize, ySize);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);      
    canvas.createBufferStrategy(2);
}
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new MainWindow();
        }
    });
}
}
Was it helpful?

Solution

You are using the old AWT Canvas class as the base component. This class follows the AWT painting mechanism, where there is no paintComponent method and you were supposed to override paint to do custom graphics.

Change the base class to JComponent and you can use the newer painting mechanism:

...
import javax.swing.JComponent;

public class GameCanvas extends JComponent {

This article compares how painting works in AWT and Swing if you want to know more about them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top