Tuesday, January 26, 2010

Simple Calculator Using Swing Part II

I talked about some GUI components that you can use in my previous post. In this post, I will explain to you how to use those GUI components.

Buttons and Text Fields are useless unless they do something, right? Some actions are triggered if you click a button. So far what we have is just display. You can run the code and will see that nothing happens when you click a button. So, now, I am going to implement an action method. Here's the code snippet : (You can click on the code to see it bigger)

You just call addActionListner() of JButton. addActionListner() take an ActionListener object. As you see it, we're passing our class SimpleCalculator to addActionListener(). ActionListener is an abstract class that has the method actionPerformed(). An abstract class has methods that haven't been implemented. So, whatever class that uses abstract class have to implement those methods in the abstract class. In ActionListener abstract class, there's an actionPerformed method. So we're going to write the code for actionPerformed method in our class. Also, you need to make sure that you declare :

public class Calculator implements ActionListener

and here's our actionPerformed() method.


The logic here is simple. Now, when you click the number buttons, you should be able to those in the text field.

No comments:

Post a Comment