Skip to main content

Java GUI Tutorial – Part 2

Introduction

This tutorial will teach you about Graphical User Interfaces, or GUI’s. GUI’s are important because it’s an effective way for the user to interact with the program. The way Java allows you to create GUI’s is the Abstract Windowing Toolkit, or AWT. Up until now you’ve only learned how to make a nice looking GUI, what you’ll learn now will teach you how to make them actually *DO* stuff! You do this using the java.awt.event.* package. Well, time to start learning events!

Setting Up Your Program

To receive events, first you have to include some packages and an interface or two. An interface is something which adds to your programs functionality. First, you must import the java.awt.event.* package:

import java.awt.event.*;

Next, you need to include one of the EventListener interfaces. This applet includes the ActionListener interface:

public class MyApplet extends java.applet.Applet implements ActionListener {

The EventListener interfaces enable a component of a graphical user interface to generate user events. Without one of the listeners in place, a component cannot do anything that can be heard by other parts of a program. A program must include a listener interface for each type of component it wants to listen to. If you need to include multiple interfaces, separate them with a coma:

public class MyApplet extends java.applet.Applet implements ActionListener, MouseListener {

Well, that’s all you need to do to set up your program to listen for events. Next you need to make your components generate the events.

Let Your Buttons Be Heard!

After you let your program listen for the events, your components must generate them. To let a component generate an event, you use the addActionListener() method. For example, to make a button generate events, you would type:

Button clearForm = new Button(“Clear”);

clearForm.addActionListener(this);

That code produces a regular looking button which generates an event. The this statement means the current class. The code creates a button and tells it to direct all events to this class to be dealt with.

How To Handle Events

When an event is generated by a component, it is sent to the specified class to be handled. Each EventListener has it’s own method to be called. For example, with the clear form button the method that would be called is the actionPerformed() method. This is what the method looks like:

public void actionPerformed(ActionEvent evt) {
    // method goes here
}

If there is only one component that will generate an event, you can put the code to handle that object’s event right in the method. However, if there is more than one object that can generate an event, you’ll need to find out which one did it. To do that you can use the getActionCommand() function:

String cmd = evt.getActionCommand();

The getActionCommand() sends back a string. If the object is a button, it’ll be the caption of that button. If it’s a text field, it’ll send the text. To get the actual object that created the event, you can use the getSource() function. This will decide which object generated the event, between a Button named fred, a text field named Texty, and another text field named James (hey, I was feeling creative):

public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
               if (source == fred) {
                 //Fred (the button) caused the event
               }
               else if (source == Texty) {
                         //Texty (the text field) caused the event
               }
               else if (source == James) {
                   //James (the other text field) cause the event
               }
}

The getSource() function works with all objects to see which one caused the event.

Check Box/Radio Button Events

Check boxes and radio buttons (aka choice boxes) require a different ActionEvent interface – namely the ItemListener interface. The following code produces a check box and adds the item listener stuff:

Checkbox goodTutorial = new Checkbox("Good tutorial?", true);
goodTutorial.addItemListener(this);

Also, checkboxes receive events through the itemStateChanged() method. To see which checkbox caused the event, you can use the getItem() method. To check what value the checkbox or radio button has, you can use the getState() method. This will check which of two checkboxes caused the event and what value they are in:

public void itemStateChanged(ItemEvent event) {
               String command = (String) event.getItem();
               if (command == "Item One's Caption") {
                               boolean value = item1.getState();
                               if (value == true) {
                                    //It's selected
                                     showStatus("Item 1 true");
                              }
                               else {
                                   //It's not selected)
                                   showStatus("Item 1 false");
                               }
               }
               else if (command == "Item Two's Caption") {
                               boolean value = item2.getState();
                               if (value == true) {
                                              //It's selected
                                  showStatus("Item 2 true");
                               }
                               else {
                                              //It's not selected)
                                   showStatus("Item 2 false");
                               }
               }
}

Yah... that code will check which of the two checkboxes has been changed, and then gets the value it’s been changed to, and then displays the message in the status bar. Run the applet to check it out, it’s pretty cool.

Text Field Events

If you want to get the text that’s in a TextField before someone presses a button, you can do that as it’s changed. You do it with the textValueChanged method:

public void textValueChanged(TextEvent txt) {

Object source = txt.getSource();

if (source == name) {

showStatus(“Name “ + name.getText());

}

else {

showStatus(“Age “ + age.getText());

}

}

Miscellaneous

How to enable and disable components – You may have seen some components grayed out so you can’t edit them. Well, this is done with the setEditable(boolean) method. For example, this will let someone enable the button named fred:

fred.setEditable(true);

This will make it so it cannot be edited by users and is grayed out:

fred.setEditable(false);

Comments

Popular posts from this blog

WAP to calculate the monthly telephone bills as per the following rule: Minimum Rs. 200 for upto 100 calls. Plus Rs. 0.60 per call for next 50 calls. Plus Rs. 0.50 per call for next 50 calls. Plus Rs. 0.40 per call for any call beyond 200 calls.

  #include<iostream.h> #include<conio.h> void main() { int calls; float bill; cout<<" Enter number of calls : "; cin>>calls; if (calls<=100) bill=200; else if (calls>100 && calls<=150) { calls=calls-100; bill=200+(0.60*calls); } else if (calls>150 && calls<=200) { calls=calls-150; bill=200+(0.60*50)+(0.50*calls); } else { calls=calls-200; bill=200+(0.60*50)+(0.50*50)+(0.40*calls); } cout<<" Your bill is Rs. "<<bill; getch(); }   Output: Enter number of calls : 190 Your bill is Rs.250

Write a program to calculate the total expenses. Quantity and price per item are input by the user and discount of 10% is offered if the expense is more than 7000.

  #include<iostream.h> #include<conio.h> void main() { int totalexp, qty, price, discount; cout<<" Enter quantity: "; cin>>qty; cout<<" Enter price: "; cin>>price; totalexp=qty*price; if (totalexp>7000) { discount=(totalexp*0.1); totalexp=totalexp-discount; } cout<<" Total Expense is Rs. "<<totalexp; getch(); }