I’ve followed these tutorials and produced the following.
http://www.youtube.com/playlist?list=PL54DB126285ED0420
Main.java:
public class Main extends JFrame {
GamePanel gp;
public Main() {
gp = new GamePanel();
setSize(500, 400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(gp);
}
public static void main(String[] args) {
Main m = new Main();
}
}
GamePanel.java:
public class GamePanel extends JPanel implements Runnable {
// Double Buffering Variables
private Image dbImage;
private Graphics dbg;
// JPanel Variables
static final int GWIDTH = 500, GHEIGHT = 400;
static final Dimension gameDim = new Dimension(GWIDTH, GHEIGHT);
// Game Variables
private Thread game;
private volatile boolean running = false;
public GamePanel() {
setPreferredSize(gameDim);
setBackground(Color.WHITE);
setFocusable(true);
requestFocus();
// Handle all key inputs from the user
addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {}
@Override public void keyReleased(KeyEvent e) {}
@Override public void keyTyped(KeyEvent e) {}
});
}
public void run() {
while (running) {
gameUpdate();
gameRender();
paintScreen();
}
}// END run
private void gameUpdate() {
if (running && game != null) {
// update the game state
}
}
private void gameRender() {
// create the buffer
if (dbImage == null) {
dbImage = createImage(GWIDTH, GHEIGHT);
if (dbImage == null) {
System.err.println("dbImage is still null!!!");
return;
} else {
dbg = dbImage.getGraphics();
}
}
// Clear the screen
dbg.setColor(Color.WHITE);
dbg.fillRect(0, 0, GWIDTH, GHEIGHT);
// Draw the game elements
draw(dbg);
}
// draw all game content
public void draw(Graphics g) {}
private void paintScreen() {
Graphics g;
try {
g = this.getGraphics();
if (dbImage != null && g != null)
g.drawImage(dbImage, 0, 0, null);
// For Linux
Toolkit.getDefaultToolkit().sync();
g.dispose();
} catch (Exception e) {
System.err.println(e);
}
}
public void addNotify() {
super.addNotify();
startGame();
}
private void startGame() {
if (game == null || !running) {
game = new Thread(this);
game.start();
running = true;
}
}
public void stopGame() {
if (running)
running = false;
}
private void log(String s) {
System.out.println(s);
}
}
It should just print a “Hello World” string on the screen but it’s not performing. I’ve gone over the code couple of times but couldn’t see what was wrong.
So what’s absent that causes it not to display the string.
Thanks.
All right. Finally just found it.
In my Main.java I’d to place the
add(gp);code to the top. Because basically it was falling under.P.S. Just mentioning again. Accidentally I erased the contents of the draw method. Silly of me. Sorry for that. It should’ve
g.drawString("Hello World!", 100, 100);in it.Thanks.