Play Around with the Window

Learn to pack a window according to the content in it, disable resizing, bring a window to center and set title.

Packing a window

How do you know what size to make the window? Instead of choosing a size for a window, you can pack the window. Java then makes the window only as large as needed to hold the window’s contents.

Adding more yes/no answers

Give Wizard of Yes/No a little personality by providing several ways to say yes or no.

  1. Add several more yes and no strings to ANSWER. Add the same number of yes answers as no answers. You can use the same array content as below.
...
private static final String[] ANSWER = {
        "Yes.",
        "Go for it!",
        "Yes, definitely.",
        "For sure!",
        "I would say yes.",
        "Most likely yes.",
        "No.",
        "I wouldn't.",
        "In my opinion, no.",
        "Definitely not!",
        "Probably not.",
        "It is very doubtful."
    }
...

After making the above changes, run it. Our program will now randomly choose between the yes and no answers each time it is run.

Making all the answers fit

The short answers fit in the window, but the long answers did not.

  1. Call pack() exactly as shown, instead of setSize().
...
  public WizardOfYesNo() {
    ...
    add(label);
    pack();
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
...

When you are done making changes in the playing area, click the run button. The window will now be automatically sized to hold the answer that is displayed.

The pack() method is used to set the window to the smallest size that will hold the window’s contents.

Disabling resizing

If you don’t want the program user to change the size of a window, disable resizing.

Restricting the window size

There is no need for the program user to change the size of Wizard of Yes/No’s window. In fact, if the user makes the window smaller, the answer won’t fit.

  1. Enter the code, exactly as shown, to disable resizing. Use JFrame's setResizable() method with false as its parameter value.
...
public WizardOfYesNo() {
     ...
     add(label);
     setResizable(false);
     pack();
     setVisible(true);    
     setDefaultCloseOperation(EXIT_ON_CLOSE);
...

NOTE: Always call setResizable() before you call pack().

When you follow the above statement and click the run button, you will see that the window now cannot be resized by dragging the edges of the window.

Setting the window title

The program will look a bit nicer if the game’s title is included in the window’s title bar.

  1. Set the title of the window to “Wizard of Yes/No”. Use JFrame's setTitle() method.
...
public WizardOfYesNo() {
    ...
    setTitle("________________");
    setResizable(false);
    pack();
    setVisible(true); 
    setDefaultCloseOperation(EXIT_ON_CLOSE);
...

Get hands-on with 1200+ tech skills courses.