Section 2: GUIs and Widgets


 

 

Widgets

The most commonly used GUI widgets are:

The life-cycle of a widget:

1. Declaration – Conception

JButton exit;
JLabel prompt;
JTextField input;

2. Construction – Birth

exit = new JButton ("Exit");
prompt = new JLabel ("Enter you name");
input = new JTextField (20);

3. Add to the Applet – Leave the hospital

add(prompt);
add(exit);
add(input);

4. Do something – Go to school!

input.setText("");

The complete code:

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class littleprog extends Applet implements ActionListener
{
    JLabel prompt;
    JTextField input;
    JButton exit;
    public void init ()
    {
        prompt = new JLabel ("Enter you name");
        input = new JTextField (20);
        exit = new JButton ("Hi");
        exit.setActionCommand ("hi");
        exit.addActionListener (this);
 
        add (prompt);
        add (input);
        add (exit);
    }

    public void actionPerformed (ActionEvent e)
    {
        if ("hi".equals (e.getActionCommand ()))
        {
            prompt.setText ("Hi " + input.getText ());
        }
    }
}

Section 3: Objects

An object is a set of data and the operations on that data.

 

1. Example: A Button

 

It’s Data – font, background colour, foreground colour, label

It’s Operations– setLabel, setBackground, getLabel, setForeground

 

·         To code to make an object is written in a class

·         An object’s class has variables to store data and methods to do things to the data.

·         To call a method to change a variable in an object, you write:

b1.setLabel(“Click 2X”);

variable-name. Method-name (information needed)

·         A Class that makes an object has a special method called a constructor.

·         The constructor is used to set up the variables in the class

·         The constructor is called like this: 

b1 = new Button (“Click Here”);
variable name = new Constructor-name(Information needed)

2. Object Comparison

 

  Button Label TextField
Class name JButton JLabel JTextfield
Variables in it - font
- background colour
- foreground colour
- label
- font
- background colour
- foreground colour
- text
- font
- background colour
- foreground colour
- text in it
Declare JButton b1; JLabel lbl1; JTextfield txt1;
Constructor b1 = new JButton("click"); lbl1=new JLabel ("Hi"); txt1=new JTextfield(15);
Other Methods b1.setBackground(Color.red);
b1.setLabel("Hi");
lbl1.setBackground(Color.red);
lbl1.setText("Hi");
txt1.setBackground(Color.red);
txt1.setText("Hi");
Add to applet add(b1); add(lbl1); add(txt1);