Evan Waddicor
Evan Waddicor

Reputation: 111

Finding Screen Size

I am trying to find the size of the screen and use it to dimension a window.

JFrame window = new JFrame(); 
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
int Width = screenSize.getWidth(); 
int Height = screenSize.getHeight(); 
window.setSize(Width, Height); 
window.setVisible(true); 
window.setTitle("Game"); 
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

It gives me the following errors:

Game.java:7: error: cannot find symbol
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
        ^
  symbol:   class Dimension
  location: class Game
Game.java:7: error: cannot find symbol
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
                               ^
  symbol:   variable Toolkit
  location: class Game
2 errors

Tool completed with exit code 1

Upvotes: 1

Views: 502

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

Did you remember to import java.awt.Toolkit?

Besides, this is a really bad way to do this, this will expand under the "extra" content that many OSs have on the screen (the TaskBar on Windows for example), and will be displayed underneath it.

Instead, you could use JFrame#setExtendedState and pass it JFrame. MAXIMIZED_BOTH which maximise the window so it fills the entire application viewable area.

Now, if you REALLY want the window to occupy the ENTIRE screen, you're going to have take a look at Full screen exclusive mode, which will bring it's own issues

If you want to know the "viewable" size of a screen (that is the area which application windows should appear within), you could use something like...

Rectangle bounds = new Rectangle(0, 0, 0, 0);

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();

GraphicsConfiguration gc = gd.getDefaultConfiguration();
bounds = gc.getBounds();

Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);

Which will return the viewable space of the desktop minus all the system stuff...

Upvotes: 2

Related Questions