Swing
Labels and text fields
Labels
Two panels that display labels
Common constructors and methods of the JLabel class
| Constructor | Description |
|---|---|
| JLabel() | Creates a blank label. |
| JLabel(String) | Creates a label with the text specified by the string. |
| Method | Description |
|---|---|
| getText() | Returns the text in this text field as a String. |
| setText(String) | Sets the text in this field to the specified string. |
How to work with labels
- The JLabel class defines a label component that can be used to display text on the panel.
- If you need to refer to a label in code, you can
- assign it to a variable and then add that variable to the panel or
- create the label and add it to the panel in a single statement.
A class that creates the Label One panel
class LabelPanel extends JPanel
{
private JLabel labelOne;
public LabelPanel()
{
labelOne = new JLabel("Label One");
this.add(labelOne);
}
}
A class that creates the Future Value panel
class FutureValuePanel extends JPanel
{
public FutureValuePanel()
{
this.setLayout(new FlowLayout(FlowLayout.RIGHT));
this.add(new JLabel("Monthly Payment:"));
this.add(new JLabel("Yearly Interest Rate:"));
this.add(new JLabel("Number of Years:"));
this.add(new JLabel("Future Value:"));
}
}