Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (115)
games submitted by our members
Games in WIP (562)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Graphics flickering  (Read 1888 times)
0 Members and 1 Guest are viewing this topic.
Offline J Dick

Junior Member


Medals: 1
Projects: 1



« Posted 2010-01-05 01:05:37 »

Hello,

Im quite new to java programmming, but i made a dos tetris game about 10 years ago with c++ so i know some programming.

Im currently making my first javagame. It needs 2d graphics so im using graphics 2d. I understand it makes a doublebuffer but my graphics are still flickering.

I get no flickering on the graphics that are not moving. But moving my players on the field makes them flicker a bit. And if I try to use g.drawString(player.name,player.x,player.y); to show the players name under the player while he is moving, the text flickers like mad.

My game runs in windowed mode.

So, any ideas why my doublebuffered game graphics are flickering?
Offline teletubo
« League of Dukes »

JGO Ninja


Medals: 48
Projects: 4
Exp: 8 years



« Reply #1 - Posted 2010-01-05 01:47:40 »

Well probably you're not buffering it right Smiley

create an offscreen image . render your scene to its Graphics2D   - that is , everything . background, characters, and stuff . 
Only after completing the above step , draw the offscreen Image to the screen. That's just about it .

Offline trembovetski

Senior Member




If only I knew what I'm talking about!


« Reply #2 - Posted 2010-01-05 21:19:51 »

We'd need to know more about how you're using the double buffering.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline J Dick

Junior Member


Medals: 1
Projects: 1



« Reply #3 - Posted 2010-01-05 22:54:28 »

Huh,

I searched for lots of tutorials about this and they only made it worse.

I finally found this one which is almost the same as my original code.

http://www.idevgames.com/forum/showthread.php?t=5301 near the bottom is an example code and it makes the text flicker like it did before, but the game runs fine.

I tried other ways also, where i used Buffered offscreen image and it caused the game to slow down very dramatically. And it didnt even look like doublebuffered. The text was flickering but very slowly.
Offline teletubo
« League of Dukes »

JGO Ninja


Medals: 48
Projects: 4
Exp: 8 years



« Reply #4 - Posted 2010-01-05 23:21:28 »

post your code then, so we can take a look

Offline Mr. Gol

Senior Member


Medals: 1



« Reply #5 - Posted 2010-01-05 23:45:59 »

Obviously posting what you actually have will result in more direct feedback, but this could also be a good place to start: http://fivedots.coe.psu.ac.th/~ad/jg/ch1/ch1.pdf It's about creating a animation loop and displaying your game in a Swing component, which seems to be what you're trying to do.
Offline J Dick

Junior Member


Medals: 1
Projects: 1



« Reply #6 - Posted 2010-01-05 23:47:21 »

Theres some of the code. Its based on coke and coke Space invaders tutorial. I couldnt post it all. Theres a 10000 character limit...

public class ThegameFrame extends Canvas implements MouseListener {
   
   
   /** The stragey that allows us to use accelerate page flipping */
   private BufferStrategy strategy;

public ThegameFrame() {
        
        JFrame container = new JFrame("Death Match");
      
      // get hold the content of the frame and set up the resolution of the game
      JPanel panel = (JPanel) container.getContentPane();
      panel.setPreferredSize(new Dimension(1024,768));
      panel.setLayout(null);
      
      // setup our canvas size and put it into the content of the frame
      setBounds(0,0,1024,768);
      panel.add(this);
      
        addMouseListener(this);

// finally make the window visible
      container.pack();
      container.setResizable(false);
      container.setVisible(true);
      
      setIgnoreRepaint(true);
      container.setIgnoreRepaint(true);
      panel.setIgnoreRepaint(true);
      
      
      //Setting up Double Buffering
      createBufferStrategy(2);
      BufferStrategy strategy = getBufferStrategy();
      
      // add a listener to respond to the user closing the window. If they
      // do we'd like to exit the game
      container.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
               }
      });


public void gameLoop()
      {
      long lastLoopTime = System.currentTimeMillis();
//      long animtimer = System.currentTimeMillis();
//      long delta = System.currentTimeMillis();
      
      Random generator = new Random();

while (matchon)
      {
               
         
         // work out how long its been since the last update, this
         // will be used to calculate how far the entities should
         // move this loop
         long delta = System.currentTimeMillis() - lastLoopTime;
         lastLoopTime = System.currentTimeMillis();
         
         
         if (strategy == null)   {
            createBufferStrategy(2);
            strategy = getBufferStrategy();
         }

         // Get hold of a graphics context for the accelerated
         // surface and blank it out

         Graphics g = null;
         g = strategy.getDrawGraphics();
   
         g.setColor(Color.white);
   //      g.fillRect(0,0,1024,768);
         g.fillRect(0,0,1024,200);
         g.fillRect(0,570,1024,198);
         

                           LOTS OF DRAWING AND COUNTING HERE


g.dispose();
         
         
//         drawScreen();
         if (!strategy.contentsLost())   {
            strategy.show();
            Toolkit.getDefaultToolkit().sync();
         }

         // finally pause for a bit. Note: this should run us at about
         // 100 fps but on windows this might vary each loop due to
         // a bad implementation of timer
         try { Thread.sleep(10); } catch (Exception e) {}
      }
   }
Offline Gudradain
« Reply #7 - Posted 2010-01-06 01:09:33 »

Hello

Here is a template I use for creating my game. It's very simple
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
ackage basicGame;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class Game implements Runnable{
   
   final int WIDTH = 1000;
   final int HEIGHT = 700;
   
   JFrame frame;
   Canvas canvas;
   BufferStrategy bufferStrategy;
   
   public Game(){
      frame = new JFrame("Basic Game");
     
      JPanel panel = (JPanel) frame.getContentPane();
      panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
      panel.setLayout(null);
     
      canvas = new Canvas();
      canvas.setBounds(0, 0, WIDTH, HEIGHT);
     
      panel.add(canvas);
     
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setResizable(false);
      frame.setVisible(true);
     
      canvas.createBufferStrategy(2);
      bufferStrategy = canvas.getBufferStrategy();
     
      canvas.requestFocus();
      canvas.addMouseListener(new MouseControl());
   }
   
   private class MouseControl extends MouseAdapter{
     
   }
   
   long desiredFPS = 60;
    long desiredDeltaLoop = (1000*1000*1000)/desiredFPS;
   
    long desiredDeltaUpdate = 10;
   
   boolean running = true;
   
   public void run(){
     
      long beginLoopTime;
      long endLoopTime;
      long currentUpdateTime = System.nanoTime();
      long lastUpdateTime;
      long deltaLoop;
     
      while(running){
         beginLoopTime = System.nanoTime();
         
         render();
         
         lastUpdateTime = currentUpdateTime;
         currentUpdateTime = System.nanoTime();
         update((int) ((currentUpdateTime - lastUpdateTime)/(1000*1000)));
         
         endLoopTime = System.nanoTime();
         deltaLoop = endLoopTime - beginLoopTime;
           
           if(deltaLoop > desiredDeltaLoop){
               //Do nothing. We are already late
          }else{
               try{
                   Thread.sleep((desiredDeltaLoop - deltaLoop)/(1000*1000));
               }catch(InterruptedException e){
                   //Do nothing
              }
           }
      }
   }
   
   protected void render() {
      Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
      g.clearRect(0, 0, WIDTH, HEIGHT);
      //Drawing code here
     g.dispose();
      bufferStrategy.show();
   }

   protected void update(int deltaTime) {
      //Update code here
  }
   
   public static void main(String [] args){
      Game ex = new Game();
      new Thread(ex).start();
   }

}

Offline JL235

JGO Coder


Medals: 10



« Reply #8 - Posted 2010-01-06 07:57:58 »

Caused no issues for me, but it's probably caused by the frame re-painting itself automatically. You need to disable this when using active rendering using the 'setIgnoreRepaint' method. Second; you should also do all of the setup code before calling pack and setVisible. Typically those calls should always be last. Some code is automatically run by the classes behind the scenes which connects the frame to the display by those methods, and it's caused issues for me in the past.

My constructor for your code is:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
public Game(){
      frame = new JFrame("Basic Game");
                frame.setIgnoreRepaint( true );
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      canvas = new Canvas();
      canvas.setBounds(0, 0, WIDTH, HEIGHT);
                canvas.setIgnoreRepaint(true);
      canvas.createBufferStrategy(2);
      canvas.addMouseListener(new MouseControl());
               
      bufferStrategy = canvas.getBufferStrategy();
               
      JPanel panel = (JPanel) frame.getContentPane();
      panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
      panel.setLayout(null);
      panel.add(canvas);
               
      frame.pack();
      frame.setResizable(false);
      frame.setVisible(true);
      canvas.requestFocus();
   }

Offline J Dick

Junior Member


Medals: 1
Projects: 1



« Reply #9 - Posted 2010-01-06 12:01:31 »

I tried to use your constructor code. 

I had to move the buferstategy codes to last, because they caused the game to crash. It said something like "component must have a valid peer".

Now the game behaves like it did before.

I draw black text and background that dont move. Those look great. The players on the field are ok. I think they flicker a bit. Not much. But the white text under the ball carrying player that indicates his name flickers like mad.

      if ( ball.state == 1 || ball.state == 2 )
            {            
               g.setColor(Color.white);
               g.drawString(messageballcarrier,(int)ball.x -20,(int)ball.y + 20);
            }

I started to think that maybe I am doing doublebuffermode ok, but the ball.x double to int coordinate conversion could make some flickering kind of effect?


My current constructor code:
   
   public ThegameFrame() {
         
      JFrame frame = new JFrame("Death Match Manager");
        frame.setIgnoreRepaint( true );
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Canvas canvas = new Canvas();
      canvas.setBounds(0, 0, 1024, 768);
        canvas.setIgnoreRepaint(true);
//      canvas.createBufferStrategy(2);
//      canvas.addMouseListener(new MouseControl());
           
        canvas.addMouseListener(this);     
        canvas.addKeyListener(new KeyInputHandler());
               
//      strategy = canvas.getBufferStrategy();
               
      JPanel panel = (JPanel) frame.getContentPane();
      panel.setPreferredSize(new Dimension(1024, 768));
      panel.setLayout(null);
      panel.add(canvas);
      
      
               
      frame.pack();
      frame.setResizable(false);
      frame.setVisible(true);
      panel.setVisible(true);
      canvas.setVisible(true);
      canvas.requestFocus();

// nämä piti siirtää setvisiblen alle      
      canvas.createBufferStrategy(2);
      strategy = canvas.getBufferStrategy();
      
      
      
      
        //OMAAA
        gamestate = 1;   // 1 = Setup phase, 2 = Game on,
//        score1 = 0;
 //       score2 = 0;
        matchon = true;
        
        for ( int i = 0; i < 8; i++)
            message = " ";
      
      
      // add a key input system (defined below) to our canvas
      // so we can respond to key pressed
      
      
      // request the focus so key events come to us
//      requestFocus();
      
      
      Random generator = new Random();
      
      // ALUSTETAAN DEBUGGAUS JOUKKUEET
      
      Player player = new Player(this,"ogrelay.png",370,350,1);
      player.makeOgre();
      player.name = "Ogre dude";
      entities.add(player);
      
      for ( int i = 0; i < 9; i++)
      {
         player = new Player(this,"lay.png",generator.nextInt(300),generator.nextInt(768),1);
          player.makeHuman();
         entities.add(player);
         player.name = "Lineman dude";
         if ( i == 6)
         {
            player.name = "Wing dude";
            player.position = 3;   //WING
         }
         if ( i == 5)
         {
            player.name = "Thrower dude";
            player.position = 2;   //THrower
         }
      }
      player.name = "Wing dude 2";
      player.position = 3;   //WING
      
      for ( int i = 0; i < 10; i++)
      {
         player = new Player(this,"xlay.png",(generator.nextInt(300)+700),generator.nextInt(768),2);
          player.makeHuman();
         entities.add(player);
         player.name = "Lineman dude";
         if ( i == 6)
         {
            player.name = "Wing dude";
            player.position = 3;   //WING
         }
         if ( i == 5)
         {
            player.name = "Thrower dude";
            player.position = 2;   //THrower
         }
      }
      player.name = "Wing dude 2";
      player.position = 3;   //WING

//         container.setIgnoreRepaint(true);
//      panel.setIgnoreRepaint(true);

      
      }
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline J Dick

Junior Member


Medals: 1
Projects: 1



« Reply #10 - Posted 2010-01-06 14:10:55 »

Im starting to find the problem Cheesy

The doublebuffering is working ok, im quite sure, and allways was working.

I tried to draw every players name under them and it worked ok Cheesy no flickering.

There must be some bug in the codes between the ball and the player carrying it, that causes it not to draw the text every cycle.

Well, thanks for your help anyways Cheesy

status = feeling dumb;
Offline Gudradain
« Reply #11 - Posted 2010-01-06 20:06:46 »

Caused no issues for me, but it's probably caused by the frame re-painting itself automatically. You need to disable this when using active rendering using the 'setIgnoreRepaint' method. Second; you should also do all of the setup code before calling pack and setVisible. Typically those calls should always be last. Some code is automatically run by the classes behind the scenes which connects the frame to the display by those methods, and it's caused issues for me in the past.

Hello,

I agree with you for the setIgnoreRepaint (still it doesn't change a lot but it's better to have it)

But your second point is half wrong. You absolutely need to make your frame visible before doing createBufferStrategy(2) or it will cause an error. But I could have put the mouseListener before making it visible.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

radar3301 (9 views)
2014-09-21 23:33:17

BurntPizza (28 views)
2014-09-21 02:42:18

BurntPizza (18 views)
2014-09-21 01:30:30

moogie (20 views)
2014-09-21 00:26:15

UprightPath (27 views)
2014-09-20 20:14:06

BurntPizza (29 views)
2014-09-19 03:14:18

Dwinin (46 views)
2014-09-12 09:08:26

Norakomi (74 views)
2014-09-10 13:57:51

TehJavaDev (102 views)
2014-09-10 06:39:09

Tekkerue (50 views)
2014-09-09 02:24:56
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!