November Black Friday Python week
This week up to 80% off on Python courses. More info
Black friday is here! Get up to 80 % extra points for free! More info

Lesson 3 - Java GUI - Event

In the previous lesson, Java GUI - Basic Components, we created a simple calculator. However, the calculator doesn't perform addition yet. In today's lesson, we're going to make it add whole numbers :-) In Java, we're going to do it using events.

Steps

  1. The user initiates an action, for example by clicking a button
  2. An event listener is assigned to the button - it's an instance of a newly created class into which we'll implement methods
  3. The system calls the method, and something happens

So let's go step by step through it. We'll create a class named e.g. EventSum in our Gui class so it can access our components. We'll implement methods from the ActionListener class in this class using the implements keyword. Your IDE should offer you to implement all the methods automatically. Anyway, we'll write it manually. The ActionListener class contains only one void method - actionPerformed(ActionEvent e). The code looks as follows:

public class EventSum implements ActionListener {

    public void actionPerformed(ActionEvent e) {

    }

}

Now we'll create an event listener - an object named sum for example. It's an instance of the EventSum class. Next, we'll add the listener to the button as a parameter of the addActionListener() method. The code will look like this:

addBut = new JButton("Add");
panel1.add(addBut);
EventSum sum = new EventSum();
addBut.addActionListener(sum);

We've completed everything essential, and now we can continue with what happens when we click the button. The code to be executed is in the body of the actionPerformed(ActionEvent e) method. We want to add the numbers that we entered into the JTextField components. But first of all, we have to get the text from them. To do this, we use the getText() method. However, the text we get is of the String type. Since we can't add strings, so we have to convert them to the Integer types:

int firstNumber = Integer.parseInt(number1Field.getText());
int secondNumber = Integer.parseInt(number2Field.getText());

Next, we'll just create another variable of the int type named result, which is the sum of the two numbers. And finally, we have to print our result somewhere. We'll write it to the resultLab component using the setText() method whose parameter is the text to be displayed on it:

public class EventSum implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        int firstNumber = Integer.parseInt(number1Field.getText());
        int secondNumber = Integer.parseInt(number2Field.getText());
        int result = firstNumber + secondNumber;
        resultLab.setText("The result is: " + result);
    }

}

The main() method remains the same, we'll just set a better size and show how to prevent the window from resizing. We can do it by the window.setResizable(false) method with the boolean parameter (true/false):

public static void main(String[] args) {
    Gui window = new Gui();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    window.setSize(220, 120);
    window.setLocationRelativeTo(null);
    window.setResizable(false);
}

Because it's impractical having to create a new class and an instance of it for every component, an anonymous inner class is usually used as the listener object. The code will be clearer and simpler. The resulting class looks like this:

public Gui()
{
    super("Calculator");
    FlowLayout layout = new FlowLayout();
    setLayout(layout);

    Color color = new Color(150, 75, 130);

    panel1 = new JPanel();
    panel1.setBackground(Color.red);
    add(panel1);

    panel2 = new JPanel();
    panel2.setBackground(color);
    add(panel2);

    number1Field = new JTextField("Number 1", 5);
    panel1.add(number1Field);

    number2Field = new JTextField("Number 2", 5);
    panel1.add(number2Field);

    addBut = new JButton("Add");
    panel1.add(addBut);
    addBut.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    int firstNumber = Integer.parseInt(number1Field.getText());
                    int secondNumber = Integer.parseInt(number2Field.getText());
                    int result = firstNumber + secondNumber;
                    resultLab.setText("The result is: " + result);
                };
            });


    resultLab = new JLabel("The result is. ");
    panel2.add(resultLab);
}

The resulting window looks something like this:

The program works if you enter integers. I'll describe the handling of the exception in the next lesson, . We'll also add other features to the calculator and we'll show how to work with another component called JComboBox (a drop-down menu) :-)


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Previous article
Java GUI - Basic Components
All articles in this section
Java Swing without a GUI designer
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!