Add text to the Window

Next, we will add text to the window or randomly select text out of an array.

Adding a label

  1. In the constructor, add code as shown below to create a JLabel object called label, with the text “Hello World”.
  2. Add code exactly as shown to add the label to WizardOfYesNo.
...
public WizardOfYesNo() {
    JLabel label = new JLabel("Hello World");
    add(label);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}
...

After implementing the above changes. Click on the Run button in the widget at the end of the lesson. Now, the window will appear with the “Hello World” text on it.

Changing the label text

We can put any text in a window. What would we have to change to make the window’s text read “Yes”?

  1. The answer is simple. We just have to change the text for label to “Yes”.
public WizardOfYesNo() {
    ...
    JLabel label = new JLabel(________);
    add(label);
    ...
}

Get hands-on with 1200+ tech skills courses.