Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #30421 > unrolled thread

NEED JAVA GRAPHICS HELP

Started bybluebeatbang@gmail.com
First post2014-11-26 09:37 -0800
Last post2014-11-26 15:43 -0800
Articles 2 — 2 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  NEED JAVA GRAPHICS HELP bluebeatbang@gmail.com - 2014-11-26 09:37 -0800
    Re: NEED JAVA GRAPHICS HELP Knute Johnson <eternal@knutejohnson.com> - 2014-11-26 15:43 -0800

#30421 — NEED JAVA GRAPHICS HELP

Frombluebeatbang@gmail.com
Date2014-11-26 09:37 -0800
SubjectNEED JAVA GRAPHICS HELP
Message-ID<3acddbde-4150-4384-9610-3622c67dccd9@googlegroups.com>
I have 3 classes and everything seems to be right but the program doesn't show anything!
WHen I compile it, a new 1000 x 700 panel is shown, but nothing is drawn on the screen!
(My paint method is render() )
Thanks for help! :)


Main class:




	public class Main extends Canvas implements Runnable {
		
		public static final int WIDTH = 1000, HEIGHT = 700;
		public static boolean running = false;
		public Thread gameThread;
		
		public int grassX = -2000, grassY = -1400;

		
		//private Object obj
		private Background bg;
		
		public void init()
		{
			//obj = new Object();
			//this.addKeyListener(obj);
			bg = new Background();
			
		}
		
		public synchronized void start()
		{
			if(running)return;
			running = true;
			gameThread = new Thread(this);
			gameThread.start();
		}
		
		public synchronized void stop()
		{
			if(!running)return;
			running = false;
			try {
				gameThread.join();
			} catch (InterruptedException e) {e.printStackTrace();}
		}
		
		public void run()
		{
			init();
			long lastTime = System.nanoTime();
			final double amountOfTicks = 60D;
			double ns = 1000000000 / amountOfTicks;
			double delta = 0;
			
			while(running)
			{
				long now = System.nanoTime();
				delta += (now - lastTime) / ns;
				lastTime = now;
				if(delta >= 1)
				{
					tick();
					//COUNTERS HERE
					
					//COUNTERS END
					delta--;
				}
				render();
			}
		}
		public void tick()
		{
			
		}
		
		public void render()
		{
			BufferStrategy bs = this.getBufferStrategy();
			if(bs == null)
			{
				createBufferStrategy(3);
				return;
			}
			
			Graphics g = bs.getDrawGraphics();
			//RENDER
			bg.render(g);
			//END RENDER
			g.dispose();
			bs.show();
		}
		
		public static void main(String[] args)
		{
			Main game = new Main();
			game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
			game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
			game.setMinimumSize(new Dimension(WIDTH, HEIGHT));
			
			JFrame frame = new JFrame("Game");
			frame.setSize(WIDTH, HEIGHT);
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setResizable(false);
			frame.add(game);
			frame.setVisible(true);
			
			game.start();
			
			
		}
		
	}


Background class:





public class Background {
	
	public static int grassX = -2000, grassY = -1400;
	
	public void render(Graphics g)
	{
		Tiles.grass(g);
	}
	
}


Tiles Class:




public class Tiles {
	
	
	public static void grass(Graphics g)
	{
		while(Background.grassY <= 2800 + 700)
		{
			while(Background.grassX <= 5000)
			{
				g.setColor(new Color(0, 232, 0));
				g.fillRect(Background.grassX, Background.grassY, 10, 10);
				g.setColor(new Color(0, 128, 0));
				g.drawRect(Background.grassX, Background.grassY, 10, 10);
				Background.grassX += 10;
			}
			Background.grassY += 10;
		}
	}

}

[toc] | [next] | [standalone]


#30429

FromKnute Johnson <eternal@knutejohnson.com>
Date2014-11-26 15:43 -0800
Message-ID<m55ohs$t47$1@dont-email.me>
In reply to#30421
On 11/26/2014 09:37, bluebeatbang@gmail.com wrote:
> I have 3 classes and everything seems to be right but the program doesn't show anything!
> WHen I compile it, a new 1000 x 700 panel is shown, but nothing is drawn on the screen!
> (My paint method is render() )
> Thanks for help! :)

Rather than nit-pick through your code, why don't you look at this 
example that works and maybe reorganize yours a little first.

package com.knutejohnson.cookbook;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;

/**
  * Demonstrates the use of a BufferStrategy to do fast drawing for 
animation.
  *
  * A BufferStrategy can be used with a Canvas or a Window.  This includes
  * Frame, JFrame and JWindow as they all extend Window.  This example 
uses a
  * JFrame to display a Canvas on which the animation drawing is done. 
Both the
  * flip buffer strategy and the blit buffer strategy are very fast and work
  * well for animation.  When the BufferStrategy is created the system will
  * use the best strategy available.
  * <p>
  * There are two timing gate methods, smoothGate and lowResourceGate.
  * Both are used to control the drawing rate by adding a delay to the
  * animation thread.  Try running this example with and without a 
timing gate.
  * <p>
  * The smoothGate method loops as fast as the processor will allow 
until the
  * time delay for the desired frame rate has elapsed.  On a modern computer
  * with many processors and cores there is still adequate processor power
  * available to run other programs even if one of the cores is saturated.
  * <p>
  * The lowResourceGate method loops around a Thread#sleep call and as a
  * result uses considerably less processor power than the smoothGate 
method.
  * The trade off is that the lowResourceGate method is not a consistent as
  * the smoothGate method and requires some tweaking to get the frame rates
  * accurate.  This is caused by the unpredictability of Thread#sleep.
  *
  * @author  Knute Johnson
  *
  * @see BufferStrategy
  */
public class DrawStrategy extends Canvas implements Runnable {
     /** Display increment angle in radians */
     private static final double ANGLE_INCREMENT = 0.0005;

     /** Animation thread */
     private final Thread thread;

     /**
      *
      * This variable is volatile because it is written to by one thread and
      * read by another.
     */
     private volatile boolean runFlag;

     /** Timer for rate display */
     private final java.util.Timer timer;

     /** TimerTask for rate display */
     private final java.util.TimerTask timerTask;

     /**
      * Current drawing angle in radians.
      *
      * This variable is thread constrained to the animation thread.
     */
     private double radians;

     /**
      * Frame count for rate display.
      *
      * This variable is volatile because it is written to by one thread and
      * read by another.
      */
     private volatile long frameCount;

     /**
      * Frame rate for rate display.
      *
      * This variable is volatile because it is written to by one thread and
      * read by another.
      */
     private volatile double frameRate;

     /**
      * BufferStrategy.
      *
      * This variable is thread constrained to the animation thread.
      */
     private BufferStrategy strategy;

     /**
      * Constructs the component, creates the animation thread, and creates
      * a TimerTask to update the frame rate display.
      */
     public DrawStrategy() {
         // give the component a starting size
         setPreferredSize(new Dimension(400,300));

         // create the animation thread
         thread = new Thread(this,"Animation Thread");

         // create the animation timer as daemon so we don't have to 
explicitly
         // stop it when the program ends
         timer = new java.util.Timer("Rate Display Timer",true);

         // update the variable frameRate
         timerTask = new java.util.TimerTask() {
             // time of last frame rate update
             long then=0;
             // frame count of last frame rate update
             long lastCount=0;

             @Override public void run() {
                 long now = System.nanoTime();
                 long frames = frameCount - lastCount;
                 double duration = (now - then) / 1000000000.0;
                 then = now;
                 lastCount = frameCount;
                 frameRate = frames / duration;
             }
         };
     }

     /**
      * Starts the animation thread and the rate display timer
      */
     public void start() {
         runFlag = true;
         thread.start();
         timer.scheduleAtFixedRate(timerTask,0,1000);
     }

     /**
      * The animation thread adjusts animation values, renders the 
drawing, and
      * displays it on the component.
      */
     @Override public void run() {
         // the last time the gate was opened
         long then = 0;

         // might as well
         thread.setPriority(Thread.MAX_PRIORITY);

         strategy = getBufferStrategy();

         while (runFlag) {
             // adjust display values
             radians += ANGLE_INCREMENT;
             ++frameCount;

             // delay gate to control frame rate
//            then = smoothGate(then,200);
//            then = lowResourceGate(then,50);


             // draw the image on the component
             do {
                 do {
                     // get the graphics from the buffer strategy
                     Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
                     // render the animation
                     render(g);
                     // must explicitly dispose
                     g.dispose();
                 } while (strategy.contentsRestored()) ;
                 // display the next buffer in the sequence
                 strategy.show();
             } while (strategy.contentsLost()) ;
         }
     }

     /**
      * Stops the animation thread
      */
     public void stop() {
         runFlag = false;
     }

     /**
      * Render the drawing to the passed in graphics context
      *
      * @param   g   graphics context
      */
     public void render(Graphics2D g) {
         int w = getWidth();
         int h = getHeight();

         // turn on anti-aliasing to get smooth drawing edges and text
         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
          RenderingHints.VALUE_ANTIALIAS_ON);

         // fill the background with white
         g.setColor(Color.WHITE);
         g.fillRect(0,0,w,h);

         // draw the frame rate in the upper left corner of component
         g.setColor(Color.RED);
         g.drawString(String.format("%.0f fps",frameRate),5,15);

         g.drawString(
          strategy instanceof Component.FlipBufferStrategy ?
          "FlipBufferStrategy" : "BltBufferStrategy",
          5,30);

         // draw the rotating blue square
         g.setColor(Color.BLUE);
         g.rotate(radians,w/2,h/2);
         g.fillRect(w/2 - 100,h/2 - 100,200,200);
     }

     /**
      * Delay method to control the frame rate of the display.
      *
      * This method uses large amounts of processor resources but is very
      * smooth and will allow very fast frame rates to be used.
      *
      * @param   then    the time the gate was last entered, from the return
      *                  value of the previous call to this method
      * @param   frameRate     the desired frame rate in frames per second
      *
      * @return          the time the gate was exited, used as input to 
the next
      *                  call to this method
      */
     public long smoothGate(long then, long frameRate) {
         long now;
         while ((now = System.nanoTime()) - then < (1000000000L / 
frameRate))
             ;

         return now;
     }

     /**
      * Delay method to control the frame rate of the display.
      *
      * This method uses very little processor resources but is not very 
smooth.
      *
      * @param   then    the time the gate was last entered, from the return
      *                  value of the previous call to this method
      * @param   frameRate     the desired frame rate in frames per second
      *
      * @return          the time the gate was exited, used as input to 
the next
      *                  call to this method
      */
     public long lowResourceGate(long then, long frameRate) {
         long now;
         while ((now = System.nanoTime()) - then < (1000000000L / 
frameRate))
             try {
                 Thread.sleep(0L,10000);
             } catch (InterruptedException ie) { }

         return now - 500000;
     }

     /**
      * Create the GUI and use a WindowListener to control startup and 
shutdown
      * of the animation thread.
      *
      * @param   args    command line arguments (not used)
      */
     public static void main(String... args) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 final DrawStrategy dS = new DrawStrategy();
                 final JFrame frame = new JFrame("DrawStrategy");
                 frame.addWindowListener(new WindowAdapter() {
                     public void windowOpened(WindowEvent we) {
                         // Create the BufferStrategy after the JFrame 
is opened
                         // so there will be a valid peer.
                         dS.createBufferStrategy(2);
                         dS.start();
                     }
                     public void windowClosing(WindowEvent we) {
                         dS.stop();
                         // Wait for the animation thread to end before
                         // disposing the frame.  This prevents an
                         // IllegalStateException if a call is made to
                         // BufferStrategy#getDrawGraphics and there is no
                         // longer a valid peer.
                         try {
                             dS.thread.join();
                         } catch (InterruptedException ie) {
                             ie.printStackTrace();
                         }
                         frame.dispose();
                     }
                 });
                 frame.add(dS,BorderLayout.CENTER);
                 frame.pack();
                 frame.setVisible(true);
             }
         });
     }
}




-- 

Knute Johnson

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web