N3mo
N3mo

Reputation: 1393

use of buffers in java graphics

I found a training for creating a 2D-graphic game on internet and base on that I wrote the code below but when I compile this nothing happens ! it just shows a window with nothing in it. by using drawString and drawLine I was really hoping to see something but the window is empty ! what's the problem ? is code wrong ? or am I using the wrong methods ?

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;
import javax.swing.JPanel;

public class Game extends Canvas {
    BufferStrategy strategy;
    boolean gameRunning = true;

        public Game() {     
            JFrame jf = new JFrame("My Graphic thingy !");

        JPanel panel = (JPanel) jf.getContentPane();
        panel.setPreferredSize(new Dimension(800, 600));
        panel.setLayout(null);

        setBounds(0, 0, 800, 600);
        panel.add(this);

        setIgnoreRepaint(true);
        jf.pack();

        jf.setResizable(false);
        jf.setVisible(true);

        jf.createBufferStrategy(2);
        strategy = jf.getBufferStrategy();

    }

    public void gameLoop() {
        long lastLoopTime = System.currentTimeMillis();
        while (gameRunning) {
            lastLoopTime = System.currentTimeMillis();

            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
            g.setColor(Color.black);
            g.fillRect(0, 0, 800, 600);
            g.drawString("HellO", 12,12);
            g.drawLine(10, 10, 30, 30);
            g.dispose();
            strategy.show();
            try {
                    Thread.sleep(2000);
            } catch (Exception e) {
            }
        }
    }
    public static void main(String[] args) {
        Game g = new Game();

        g.gameLoop();
    }

}

Upvotes: 1

Views: 245

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your current loop will likely tie up the Swing Event Dispatch Thread, or EDT, effectively freezing your application since this all important thread is prevented from doing what it must do -- rendering your application and respond to user input. You need to take threading into account by making sure that the loop is run in a background thread.

Having said that, I must question the quality, timeliness and relevance of your tutorial if it is recommending that you code with AWT components such as Canvas and if it recommends that you use null layout and absolute positioning of components (i.e., use of setBounds(...)). You will be far better off using all Swing components and Swing graphics as per the tutorials.

Please have a look at:


Edit: also,

  • You shouldn't try drawing directly to the JFrame but rather draw in a JPanel, usually in its paintComponent(...) method, although some games do things differently and use active rendering rather than the typical passive rendering.
  • Don't use the same color for your background as for your drawing text since if they are the same, you'll never see any text.

Edit 2: for example,

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.*;

@SuppressWarnings("serial")
public class Game2 extends JPanel {
   private static final int PREF_W = 800;
   private static final int PREF_H = 600;
   private static final int TIMER_DELAY = 50;
   private static final int DELTA_WIDTH = 50;
   private static final Color HELLO_COLOR = new Color(150, 150, 255);
   private int delta = 0;
   private BufferedImage img;

   public Game2() {
      img = createMyImage();
      setBackground(Color.BLACK);
      new Timer(TIMER_DELAY, new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent arg0) {
            delta++;
            repaint(delta - 10, delta - 10, DELTA_WIDTH + 20, DELTA_WIDTH + 20);
         }
      }).start();
   }

   private BufferedImage createMyImage() {
      BufferedImage myImg = new BufferedImage(DELTA_WIDTH, DELTA_WIDTH,
            BufferedImage.TYPE_INT_ARGB);
      Graphics g = myImg.getGraphics();
      g.setColor(HELLO_COLOR);
      g.drawString("Hello", 12, 12);
      g.setColor(Color.red);
      g.drawLine(10, 10, 30, 30);

      g.dispose();
      return myImg;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.drawImage(img, delta, delta, this);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Game2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Game2());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Upvotes: 5

Related Questions