Add text to the Window
Learn to add text in the window.
We'll cover the following
Next, we will add text to the window or randomly select text out of an array.
Adding a label
- In the constructor, add code as shown below to create a
JLabel
object calledlabel
, with the text “Hello World”. - 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”?
- 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.