FSEM and layout manager issue

Hi,

I’ve got a project where I’m using a BufferStrategy on a Canvas of a fixed dimension. I want the option to show this Canvas either in a standard decorated Frame or centred within a full screen (black) window. I’m using (roughly) the following code.

Dimension dim = new Dimension(width, height);
Frame frame = new Frame();
frame.setLayout(new GridBagLayout());
frame.setBackground(Color.BLACK);
canvas = new Canvas();
canvas.setMinimumSize(dim);
canvas.setPreferredSize(dim);
frame.add(canvas);
if (fullScreen) {
    frame.setUndecorated(true);
    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    gd.setFullScreenWindow(frame);
} else {
    frame.pack();
    frame.setVisible(true);
}

This works great on Linux. I tried it on Windows (7) the other day, and the canvas is rendered in the top left.

Is there something obviously wrong with this approach?
Should I be setting the size of the window explicitly before using FSEM? I was under the impression that setFullScreenWindow() sets the bounds of the window anyway?

I couldn’t find any specific examples of achieving this, so thought I’d ask here - surely someone’s done this before. Tweaks to above code, or ideas for a completely different strategy to make this work cross-platform greatly appreciated.

Thanks in advance, Neil

Sorry to bump this :persecutioncomplex:

Have also changed title to make it more obvious what I’m trying to do. Surely someone’s done this before - what daft mistake am I making???

On this thread I posted some example code on how work with a canvas in fullscreen.

http://www.java-gaming.org/index.php/topic,22661.0.html

you might want to consider making the canvas fullscreen, setting up a bufferstrategy, rendering to a volitile image, then rendering that image in the center of the screen.
or do the extra math and add offset values to each of your calls to draw.
In regards to your layout also make sure to call validate() on the frame.

I just started replying to you, and then noticed you’d added extra information. :slight_smile:

Firstly, thanks for responding.

I have seen that thread you linked to. In fact, I posted on it! (Incidentally, the fake full screen code you posted doesn’t work reliably cross-platform for the reasons I posted there.)

I had another look at the rest of the code you posted and realised that you’re using a canvas set to screen size, and realise that I could try the solution you suggest and just render an image into the centre. At the moment I’ve got my code set so that it ignores repaints on the Canvas but not on the Frame to not have the extra (probably minimal) overhead of clearing the area outside the image.

Your comment about validate() may have hit the nail on the head though. I was under the impression that setBounds() automatically revalidated everything. Googling this suggests that there may be a bug that this works differently on Linux and Windows. Will try manually setting the frame size and validating prior to FSEM and see if that works first.

Thanks for your input. I only have an IDE set up on Linux atm so makes tweaking things to test on Windows a bit awkward.

Best wishes, Neil

yeah the code posted there isnt fullscreen exclusive mode, but it wouldnt take much to add it that way.

modified version for fullscreen exclusive mode. and centered the rendering


import java.awt.Canvas;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.JFrame;

import java.awt.DisplayMode;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.MemoryImageSource;
import java.awt.image.VolatileImage;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Component;
public class FakeFullscreen implements Runnable {
	
	//SHOULD BE SET TO TRUE FOR NORMAL GAME LOGIC
	final static boolean FRAME_SYNC = true;
	final static int FRAME_RATE = 61;
	
	final static boolean STRETCH = false;
	final static boolean HIGH_QUALITY = true;
	final static boolean FULLSCREEN = true;
	
	boolean isRunning;
	CustomTimer timer;
	FPSCounter fpsCounter;
	
	
	JFrame 	frame;
	VolatileImage offScreen = null;
	BufferStrategy buffer;
	Component drawArea;
	Dimension screenSize;
	Dimension gameSize;
	Rectangle gameArea;
	Graphics2D offScreenGraphics;
	Graphics2D graphics;
	
	public FakeFullscreen() {
		
		frame = new JFrame() {
		    public void paint(Graphics g) {
		    	
		    }
		  	public void update(Graphics g) {
		    	
		    }
		  	
		};
		timer = new CustomTimer();
		fpsCounter = new FPSCounter(timer);
		final Toolkit toolkit = Toolkit.getDefaultToolkit();

		final int[] pixels = new int[16 * 16];
		final Image image = toolkit.createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
		final Cursor invisibleCursor = toolkit.createCustomCursor(image, new Point(0, 0), "invisibleCursor");

		gameSize = new Dimension(640, 480);
		screenSize = toolkit.getScreenSize();
		gameArea = new Rectangle(0, 80, 640, 400);

		frame.setAlwaysOnTop(true);
		frame.setCursor(invisibleCursor);
		frame.setIgnoreRepaint(true);
		frame.setLocation(0, 0);
		frame.setResizable(false);



		frame.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent event) {
				if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
					isRunning = false;
				}
			}
		});
		
		
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			@Override
            public void windowClosing(WindowEvent e) {
                isRunning = false;
            }
        });


		
		
		if (FULLSCREEN) {
			try {
				
				GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
		    	GraphicsDevice device = env.getDefaultScreenDevice();

		    	GraphicsConfiguration gc = device.getDefaultConfiguration();
		    	
		    	//DisplayMode displayMode = device.getDisplayMode();
	    		//if (device.isDisplayChangeSupported()) {
			    	//GraphicsDevice[] devices = env.getScreenDevices(); 
			    	//for (int i = 0; i < devices.length; i++) {
			    	//	DisplayMode dms[] = devices[i].getDisplayModes();
			    	//	for (int j = 0; j < dms.length; j++) {
			    	//		System.out.println("Device      : " + (i+1));
				    //    	System.out.println("Width       : " + dms[j].getWidth()); 
				    //    	System.out.println("Height      : " + dms[j].getHeight()); 
				    //     	System.out.println("Refresh Rate: " + dms[j].getRefreshRate()); 
				    //    	System.out.println("Bit Depth   : " + dms[j].getBitDepth()); 
				    //    	System.out.println(""); 
			    	//	}
			    	//} 
	    			//device.setDisplayMode(displayMode);

	           // } 
	    		frame.setUndecorated(true);
	    		
	    		device.setFullScreenWindow(frame);
	    		frame.setSize(screenSize);
	    		frame.setVisible(true);
	    		drawArea = frame.getContentPane();
	    		frame.toFront();
	    		frame.createBufferStrategy(2);
	    		buffer = frame.getBufferStrategy();

	    		offScreen = gc.createCompatibleVolatileImage(gameSize.width, gameSize.height);
	    		//canvas.setSize(screenSize);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			final Canvas canvas = new Canvas();
			canvas.setIgnoreRepaint(true);
			drawArea = canvas;
			canvas.setSize(gameSize);
			if (STRETCH) frame.setResizable(true);
			frame.add(canvas);
			
			frame.pack();
			frame.setVisible(true);
			frame.toFront(); 
			frame.validate();
			
			canvas.createBufferStrategy(2);
			buffer = canvas.getBufferStrategy();
			offScreen = canvas.createVolatileImage(gameSize.width, gameSize.height);
		}


		

		isRunning = true;
		
		
		new Thread(this).start();
	}

	public void run() {
		
		
		int ballWidth = 8;
		int ballHeight = 8;
		int ballX = gameArea.width / 2 - ballWidth / 2;
		int ballY = gameArea.y + (gameArea.height / 2 - ballHeight / 2);
		int ballDx = 1;
		int ballDy = 1;
		while (isRunning) {
			if (!FRAME_SYNC || timer.update(FRAME_RATE)) {
				fpsCounter.update();
				ballX += ballDx;
				ballY += ballDy;

				if (ballX <= gameArea.x) {
					ballX = gameArea.x;
					ballDx = -ballDx;
				} else if (ballX >= gameArea.width - ballWidth) {
					ballX = gameArea.width - ballWidth;
					ballDx = -ballDx;
				}

				if (ballY <= gameArea.y) {
					ballY = gameArea.y;
					ballDy = -ballDy;
				} else if (ballY >= gameArea.y + gameArea.height - ballHeight) {
					ballY = gameArea.y + gameArea.height - ballHeight;
					ballDy = -ballDy;
				}
				try {
					offScreenGraphics = offScreen.createGraphics();
					offScreenGraphics.setColor(Color.BLACK);
					offScreenGraphics.fillRect(0, 0, screenSize.width, screenSize.height);
					offScreenGraphics.setColor(Color.WHITE);
					offScreenGraphics.drawString(String.format("FPS: %s", fpsCounter.getFPS()), 20, 20);

					int renderX = (int) (ballX + ballDx);
					int renderY = (int) (ballY + ballDy);

					offScreenGraphics.drawLine(gameArea.x, gameArea.y - ballHeight, gameArea.width, gameArea.y - ballHeight);
					offScreenGraphics.fillRect(renderX, renderY, ballWidth, ballHeight);
					
					
					graphics = (Graphics2D) buffer.getDrawGraphics();
						if (STRETCH) {
							if (HIGH_QUALITY) {
								graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
								graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
							}
							graphics.drawImage(offScreen, 0, 0, drawArea.getWidth(), drawArea.getHeight(), 0, 0, gameSize.width, gameSize.height, null);	
						} else {
							graphics.setColor(Color.BLACK);
							graphics.fillRect(0, 0, drawArea.getWidth(), drawArea.getHeight());
							int offXFactor = offScreen.getWidth()/2;
							int offYFactor = offScreen.getHeight()/2;
							int midX = drawArea.getWidth()/2;
							int midY = drawArea.getHeight()/2;
							graphics.drawImage(offScreen, midX - offXFactor, midY - offYFactor, null);
						}
						

					//if (!buffer.contentsLost()) {
						buffer.show();
					//}
				} finally {
					if (offScreenGraphics != null) {
						offScreenGraphics.dispose();
					}

					if (graphics != null) {
						graphics.dispose();
					}
				} 
			}
			Thread.yield();
		}
		frame.setVisible(false);
		System.exit(0);
	}
	public static void main(String[] args) {
		new FakeFullscreen();
	}
}

class CustomTimer {
	private long timeThen;
	public CustomTimer() {
		timeThen = System.nanoTime();
	}
	public boolean update(int fps) {

		long gapTo = 1000000000L / fps + timeThen;
		long timeNow = System.nanoTime();
		if (gapTo > timeNow) return false;
		timeThen = timeNow;

		return true;
	}

	public long getTime() {
		return System.nanoTime();
	}
	public long getTimerResolution() {
		return 1000000000L;
	}
}
class FPSCounter {
	private CustomTimer timer;
	private float FPS = 0, fc = 0;

    private long
                 currentTime,
                 elapsedTime,
                 lastTime;
    
    public FPSCounter(CustomTimer timer) {
    	this.timer = timer;
        currentTime     = 0;
        elapsedTime = lastTime = timer.getTime();
    }
    public boolean update() {
		currentTime = timer.getTime();

	      fc++;
	      long updateFrequency = timer.getTimerResolution()>>1;
	      if((elapsedTime = currentTime - lastTime) >= updateFrequency){
	        FPS         = (fc/elapsedTime)*updateFrequency*2;
	        fc         = 0;
	        lastTime    = currentTime;
	        elapsedTime = 0;
	        return true;
	      }
	      return false;
    }
    public float getFPS() {
    	return FPS;
    }
}



btw. I tested it on win7