Dr. Hikmat A. M. AbdelJaber
GUI are event driven (i.e. when user interacts with a GUI component, the interaction (event) derives the program to perform a task). Event: click button, type in text field, close window, etc. Event handler: The code that performs a task in response to an event. Event handling: The process of responding to events.
Top level classes: classes not declared inside another classes. Nested classes: classes declared inside another classes. Non-static 1. Requires an object of top-level class. 2. Has a reference to top-level object. static 1. Does not require. 2. Has no reference. Inner class: can access data + methods of top-level.
inner class object Event handler (listener) [must be registered] action If event occurs
JPasswordField extends JTextField JTextField extends JTextComponent JTextComponent JTextField extends JPasswordField extends JPasswordField shows typed characters as hidden with an echo character. seteditable is inherited by JTextField from JTextComponent. JTextComponent is in javax.swing.text
object TextField Event handler (listener) [must be registered] listens If event occurs class implements ActionEvent (interface) ActionListener calls automatically ActionListener (method)
Pressing Enter ( ) generates ActionEvent. This event is processed by an object that implements the interface ActionListener. Steps required to setup event handling for GUI component: 1. Create a GUI component (e.g. TextField, Label, Button) 2. Create a class that represent the event handler. In this class, implement an appropriate event-listener interface. 3. Register the event handler. i.e. notify the handler when event occurs.
import import import import import import import java.awt.flowlayout; java.awt.event.actionevent; java.awt.event.actionlistener; javax.swing.jframe; javax.swing.joptionpane; javax.swing.jpasswordfield; javax.swing.jtextfield; public class TextFieldFrame extends JFrame { private JTextField textfield1; private JTextField textfield2; private JTextField textfield3; private JPasswordField passwordfield; public TextFieldFrame() { super("testing JTextField and JPasswordField"); setlayout(new FlowLayout()); First Program TextFieldFrame.java
textfield1 = new JTextField(10); add(textfield1); textfield2 = new JTextField("Enter text here"); add(textfield2); textfield3 = new JTextField("Uneditable text field", 21); textfield3.seteditable(false); add(textfield3); passwordfield = new JPasswordField("Hidden text"); add(passwordfield); TextFieldHandler handler = new TextFieldHandler(); textfield1.addactionlistener(handler); textfield2.addactionlistener(handler); textfield3.addactionlistener(handler); passwordfield.addactionlistener(handler); } // end constructor Step 1: Create GUI component Step 3: Register the event handler
private class TextFieldHandler implements ActionListener { public void actionperformed (ActionEvent event) { String string = ""; if (event.getsource()==textfield1) string = String.format("textField1: %s", event.getactioncommand()); else if (event.getsource()==textfield2) string = String.format("textField2: %s", event.getactioncommand()); else if (event.getsource()==textfield3) string = String.format("textField3: %s", event.getactioncommand()); else if (event.getsource()==passwordfield) string = String.format("passwordField: %s", new String (passwordfield.getpassword())); JOptionPane.showMessageDialog(null, string); } } // end inner class } // end TextFieldFrame class Step 2: Create an inner class that represent the event handler
import javax.swing.jframe; Second Program TextFieldTest.java public class TextFieldTest { public static void main(string[] args) { TextFieldFrame textfieldframe = new TextFieldFrame(); textfieldframe.setdefaultcloseoperation(jframe.exit_on_close); textfieldframe.setsize(450, 200); textfieldframe.setvisible(true); } }
Output
The information about any GUI event that occurs is stored in an object of a class such as ActionEvent, ItemEvent, TextEvent, KeyEvent, MouseEvent, ListSelectionEvent, ComponentEvent, WindowEvent, ContainerEvent, etc. Example: (10 )هذا الحدث موجود في البرنامج السابق في شريحة Public void actionperformed (ActionEvent event) {. }
Each component generates specific event object. TextField generates ActionEvent object هذا الحدث تم التعامل معه في Button generates ActionEvent object )10 المثال السابق (شريحة TextComponent generates TextEvent object JCheckBox generates ItemEvent object JRadioButton generates ItemEvent object JComboBox generates ItemEvent object JList generates ListSelectionEvent object هذا الحدث سوف نتعامل معه )22 في المثال الاحق (شريحة Mouse generates MouseEvent object Key generates KeyEvent object
For each event-object type, there is a corresponding event-listener interface. Ex: ActionEvent has ActionListener interface Some event-listener classes: ActionListener, ItemListener, KeyListener, MouseListener, ListSelectionListener, etc.
A handler class is any class that implements a listener interface that is appropriate for the type of event object generated by the component. Component generates event object when a listener object is registered with the component. The method of the component that accomplishes this is the addxxxlistener method. The xxx represents the name of the specific listener. Example: textfield1 generates ActionEvent which implements ActionListener. Therefore, textfield1.addactionlistener(handler);
The listener interface specifies the methods by which the event object can be handled. The class must implement the code for these methods. The following table shows the listener interfaces that can be implemented and their methods: Category Interface Name Methods Action ActionListener actionperformed( ActionEvent ) Item ItemListener itemstatechanged( ItemEvent ) Text TextListener textvaluechanged( TextEvent ) List ListSelectionListener valuechanged( ListSelectionEvent )
Category Interface Name Methods Key KeyListener keypressed( KeyEvent ) keyreleased( KeyEvent ) keytyped( KeyEvent ) Mouse MouseListener mousepressed( MouseEvent ) mousereleased( MouseEvent ) mouseentered( MouseEvent ) mouseexited( MouseEvent ) mouseclicked( MouseEvent ) Mouse Motion MouseMotionListener mousedragged( MouseEvent ) mousemoved( MouseEvent ) Window WindowListener windowclosing( WindowEvent ) windowopened( WindowEvent ) windowiconified( WindowEvent ) windowdeiconified( WindowEvent ) windowclosed( WindowEvent ) windowactivated( WindowEvent ) windowdeactivated( WindowEvent )
ComboBox (drop-down list) provides a list of items. ComboBox is implemented with class JComboBox JComboBox generates ItemEvent event. Show the program. Each item added to the list has an index (0, 1, 2, ). setmaximumrowcount sets the max. no. of elements that are displayed when the user clicks the JComboBox.
Anonymous inner class is a special form of inner class that is declared without a name and appears inside a method declaration. Declare event listener class, create an object of that class, and register that object as the listener for the JComboBox object ItemEvent. The declaration of an anonymous inner class, in this example, begins after ItemListener() which implements interface ItemListener.
import import import import javax.swing.*; java.awt.*; java.awt.event.itemevent; java.awt.event.itemlistener; First Program AnonymousInnerClass_ComboBox.java public class AnonymousInnerClass_ComboBox extends JFrame { private JComboBox imagesjcombobox; private JLabel label; private String names[]={"birds.gif","cat.gif","glassfish.gif","turtle.gif"}; private Icon icons[] = {new ImageIcon(getClass().getResource(names[0])), new ImageIcon(getClass().getResource(names[1])), new ImageIcon(getClass().getResource(names[2])), new ImageIcon(getClass().getResource(names[3]))}; public AnonymousInnerClass_ComboBox() { super("using Anonymous Inner Class with JComboBox"); setlayout(new FlowLayout());
imagesjcombobox = new JComboBox(names); imagesjcombobox.setmaximumrowcount(3); add(imagesjcombobox); label = new JLabel(icons[0]); add(label); imagesjcombobox.additemlistener( new ItemListener() { public void itemstatechanged(itemevent e) { if(e.getstatechange()==itemevent.selected) label.seticon(icons[imagesjcombobox.getselectedindex()]); } } ); } // end constructor } // end class Anonymous inner class
Second Program AnonymousInnerClass_ComboBox_Test.java import javax.swing.jframe; public class AnonymousInnerClass_ComboBox_Test { public static void main( String[] args) { AnonymousInnerClass_ComboBox combobox = new AnonymousInnerClass_ComboBox(); combobox.setdefaultcloseoperation(jframe.exit_on_close); combobox.setextendedstate(jframe.maximized_both); combobox.setvisible(true); } }
Develop a GUI application to place three buttons on a frame. Use event handling that is when clicking the first button the background of frame changes to red color and when clicking the second button the background of frame changes to blue color and when clicking the third button the background of frame changes to green color.
Develop a GUI application that contains three programs (i.e. three classes). The first class is used to allow the user input the correct password. When the user enters the correct password, the password frame closes and the frame of the second class opens. The second class is used to connect a database and manipulate transactions. The third class contains main method to test the other classes.