How to tell a Java JFrame to fill the entire screen

In an earlier tutorial, I shared some code on how to maximize a JFrame, but every once in a while you'll run into a situation where you want to fill an entire screen with a JFrame, but not call a method to actually maximize it. This is rare, but I just ran into this situation, so I thought I'd share the source code here.

So, here's a sample Java Swing method that demonstrates how to make a given JFrame fill the full size of the current screen:

private void makeFrameFullSize(JFrame aFrame) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    aFrame.setSize(screenSize.width, screenSize.height);
}

As you can see from the code, the method uses the Toolkit class to determine the current screen size, then sets the size of the given JFrame with the setSize method.

Setting a JFrame to fill half the screen

One good thing about sharing this code is that you can easily use adapt it to set a JFrame to other sizes. For instance, if you want to create a JFrame that is half the width and half the height of the screen, you can just divide the dimensions in half, as shown in this code:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
aFrame.setSize(screenSize.width/2, screenSize.height/2);

If you really want to maximize a JFrame ...

Again, use this link if you really want to maximize a JFrame, otherwise use the source code shown in this tutorial if you want to set the frame size to some other dimension, including setting the frame to fit the full screen size, without setting the maximize state.