Java Tutorial - lesson four


Lesson Four: Adding components in your window.

previous lesson - back to tutorial index - next lesson


We will now add two editable fields to our window, four buttons and one label. In the two fields, numbers can be written, with the buttons, we will be able to perform arithmic operations on these numbers, and the label will show the result of the operation in a later lesson.

Change the code in the Calculator class to:

import java.awt.*;
import java.awt.event.*;
//---------------------------------------------
// Class
//---------------------------------------------
public class Calculator extends Frame {
//---------------------------------------------
// Constructor
//---------------------------------------------
    public Calculator() {
        Panel panel= getWinComponents();
        this.add(panel);
        initScreen();
        this.validate();
        System.out.println("Constructing a new Calculator...");
    }
//---------------------------------------------
// Methods
//---------------------------------------------
    private Panel getWinComponents() {
        TextField numberOne= new TextField();
        TextField numberTwo= new TextField();
        Button buttonAdd= new Button("+");
        Button buttonSub= new Button("-");
        Button buttonMul= new Button("*");
        Button buttonDiv= new Button("/");
        Label result= new Label("Nothing yet...");
        Panel panel= new Panel();
        panel.add(numberOne);
        panel.add(numberTwo);
        panel.add(buttonAdd);
        panel.add(buttonSub);
        panel.add(buttonMul);
        panel.add(buttonDiv);
        panel.add(result);
        return panel;
    }
//---------------------------------------------
    private void initScreen() {
        this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0); } });
        this.setBounds(100, 100, 300, 200); this.show();
        System.out.println("End of the method initScreen...");
    }
}

 

Compile and run the programme. You will notice that indeed the components have been added, but that we cannot do anything with them yet.

Reviewing the code:
All the components are added to a panel in a new method called getWinComponents(). The components TextField, Button and Label are reusable Java elements or classes. A panel is a Java element that can contain these elements, these so-called Graphical User Interface (GUI) components. The method getWinComponents() returns a panel with all these elements. That is why the return value of the method is not of the type of void, but of the type of Panel. In the constructor, this panel is added to īthisī class, i.e., this Frame. The validate method is used as a trick to recalculate the window and the elements so the GUI components are shown immediately upon startup.

previous lesson - back to tutorial index - next lesson