You are on page 1of 5

110CSC212/110CSC318 September 2006

Lab Session 1 : Introduction to Building GUIs in Java
Objective: • To understand how to create basic GUI components in Java, and assemble them. First, copy the zip file (.zip file of 8 test programs for Lab Session 1) to your own account (compiling from here is much faster than compiling from floppy!). Example 1 (test1.java) Open the Java file test1.java (in the folder test1). This is about the simplest application program you can get to create and display a GUI object. This program creates a JFrame (Swing terminology for a Frame), with the bare minimum of userdefined properties.


Compile this program, and then Execute it.

You should see a Frame object (called f in the program), with no title, and a default grey background. Try clicking on the Maximize and Minimize icons on the top right corner of the frame. Now click on the Close icon. The frame should disappear. But... your program (application) has not terminated! To terminate it, you should close the console window. In general, for an event-driven program to terminate itself, you have either to set the ‘default close operation’ for a frame to ‘exit’, or else the program has to obey a ‘System.exit(0);’ somewhere. • Now look again at the text of this program: several lines are commented out. Uncomment one of these lines, recompile the program, and execute it again. Notice the effect of executing the new line. (Don’t forget to terminate the program!). Do this for each of the commented lines. Example 2 (test2.java) Program test2 is a restructured version of test1. It has exactly the same functionality, but since we want to create more than a bare minimum frame, we define our own class which will represent our type of frame. We do this by defining, in a separate file, a new class called ‘myFrame’ which extends the basic JFrame class: class myFrame extends JFrame ... Compile this and execute it. Compare what you see with what you expect from looking at the constructor in myFrame. Note that the application/main program (test2.java) merely creates an instance of myFrame. This is what you should aim for – the main method should just set things up and then sit back and let the objects get on with it. (Don’t forget to ‘Stop’ it).

1

) .ActionListeners (can be connected to buttons. to this frame. The programmer must supply the code for the method: actionPerformed (event e).g. and what you see on the screen. Exercise: create a fifth frame (with green background) below the existing ones. This is because we have no code to detect or respond to an event (like clicking on a button). You can click the buttons.java) Event Handling in Java If a user causes an event (e. This method does the polling. to see which one of them caused the event. (test5. They pick up events such as button clicks.java) This program starts to build up the complexity of myFrame objects. called “New” and “Cancel”. menu items. Note which variables (in each myFrame object) correspond to displayed elements: Close OK Quit this (a myFrame object) c (ContentPane of myFrame.java) This example illustrates two new things: • Creating multiple instances of the same class • Parameterising objects at creation time. they handle ‘close’ events) JButton object Instance of an ActionListener The same listener object can be connected to several objects. Some basic ones are: . and its method ‘actionPerformed’ is called. etc. 2 . (test3. we can create different kinds of ‘listener’ objects. This must check all the objects it is connected to in turn. (test4. Try changing some of the parameters. etc.WindowListeners (connected to Frames. that event will only be picked up within the program if there is an object which is connected to the GUI object and is listening out for that event – an ‘action listener’ object. but of course nothing will happen. Example 4. the appropriate listener is activated. objects are then added to c) Exercise: Add two more buttons. by clicking on a GUI object such as a button). When an event occurs. Note the correspondence between the parameters in the main program. In Java. and processes the event once it has identified its source. Example 5. menu item selections. by adding a few buttons.110CSC212/110CSC318 September 2006 Example 3.

for each button. // addActionListener Examine the program test5a. and includes the method actionPerformed which is called when any of the three buttons is clicked. } // method actionPerformed }).‘anonymous’ ActionListeners If we have a separate version of the ActionListener class for each button. and then looks to see which of its objects it was: if (ob == bClose) . Exercises: • Change the program so that is displays your name when ‘OK’ is clicked. and do the same two exercises above with this program.java.java)-.out. we can create an instance of a new.getSource(). The event handler object H is added to each button by. (test5a.. The actionPerformed method first finds out the source of the event (which button): Object ob = e.110CSC212/110CSC318 September 2006 test5..java. This method is called automatically when there is an event on one of the objects to which H is connected as an ActionListener.println("Close clicked").. etc. and add this as the button’s ActionListener: bClose. and note the output corresponding to each button (Clicking ‘Quit’ will terminate the program.java program adds event handling to test4. which change the colour of the background to Red and Yellow respectively.. Now compile and run test5. This event handler (H) is an instance of our own implementation of ActionListener. e.addActionListener(H). customised ActionListener class on the spot. then it isn’t necessary for the method actionPerformed() to poll each button in turn. so keep this to the end!) Make sure you can trace exactly where control flow goes in the program. and can understand why it displays what it does. Example 5a. To do this conveniently.. called “Red” and “Yellow”. In this program we have decided to have just one event handler which handles all events.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) /* This method is activited automatically when Close is clicked */ { System.: bClose. // one of the GUI objects which was clicked.g. 3 . • Add two more buttons to the frame.

Run the program. Save changes.java) Test7 demonstrates several things. The actual reference (std) does not change – just the contents. which throws up a sub-frame which enables the user to edit the student details (name and address). but for now we use just one student object.110CSC212/110CSC318 September 2006 Example 6. (test6.java is an alternative coding of test6. in a hierarchical way. • Image button. you can terminate the application directly. and in handling events. add a ‘DoB’ button to 4 . Exercise We want to add a ‘Date of Birth’ field to studentClass.java for how this data is held. consisting of a student number. You should upgrade studentClass. so that a frame can edit & pass back data The program first sets up a simple student record. Executing the program throws up a frame: Type some text into each of the three upper text fields.java. Note: By clicking the frame’s Close icon. this would not be passed back to the base frame as it is currently coded. See studentClass.java) This program shows the use of text fields. Then the program displays the ‘base’ frame which provides two buttons: • “Search”.EXIT_ON_CLOSE). using anonymous event handlers. Examine the code (in myFrame) to see exactly how this is achieved – both in constructing the interface. If within f2 a new student object was created. Note: test6a. and then to be able to edit this in a separate frame. In practice there should be lots of students. Then examine the code (particularly baseFrame) to track the flow of control. which retrieves and shows an image corresponding to the student number. Clicking on one of the buttons will copy the string in the text field beside the button into the bottom text field. and how to copy from one to another. and then view them. This is because myFrame constructor has set the default Close operation to ‘Exit’: setDefaultCloseOperation(JFrame. click search. and then click on the image. Example 7 (text7. • How to pass data between frames. including: • How one frame can create another. name and address (all held as strings). and either save these changes or cancels. You should make sure you understand exactly what each line of code does! Note: the reason that changes made in the secondary frame are saved in the object is that a reference to the object is passed in to f2.

the program ‘beeps’ as a reminder. and the new value is the same as the current value. Now click on a ‘Read’ button on the right hand frame. or write.beep().java) test8. There are two ‘user’ frames.java. call: Toolkit. Can you spot the line(s) responsible for initiating this update? Exercise: modify the program so that. Examine the code for text8.getDefaultToolkit().110CSC212/110CSC318 September 2006 the base frame. showing the current DoB. Example 8 (test8. Merely typing the info does nothing (it does not cause any events which the frame responds to). there is a central datastore object which holds data on a person. 5 . so they can all access it as a shared data object. They will give you experience which will be useful in doing your projects. be sure to complete them in your own time. At the same time. the viewer frame shows the current contents. Clicking on a ‘Write’ button will store the string in the text field into the object called ‘data’. Note that both user frames and the viewer frame are given the data object. String <name1> String <name2> String <address> Datastore object – just held in memory: not visible DatastoreViewer object Type some new text into the fields in the left frame. if you attempt to write a field. via which a user can read. [Note: to generate a beep. so that clicking this will give a separate frame (rather like secondFrame). each of the fields in the datastore.java demonstrates how GUI objects like text fields are just ‘windows’ on to data which is held in the program – they should not be used to store data themselves. with buttons to Save or Cancel any changes. Note: changing the contents of the datastore object does not automatically cause the viewer frame fields to be refreshed – the program contains code to do this. You should see the new field come up. In Test8. ] If you don’t manage to work through all the exercises in this assignment. A third viewer frame shows what is currently in the datastore (but can’t change it).