The previous unit, Unit 6, has shown you how to create graphical user interfaces that contain a wide range of components and have quite sophisticated layouts. You are also in a position now to make use of Java reference material to investigate and use other components and layouts. However, when the user clicks on a button or enters text, nothing happens. This is because there is no link between the graphical user interface and the code that you would like to be executed.
Creating this link between something happening in the graphical user interface – an event – and the execution of code is the subject of this unit. This subject is commonly known as event-driven programming. Event-driven programs are programs that respond to events initiated by the user, such as mouse clicks and key presses. Events can also be initiated through software coding, using for example the Timer class, which may specify that certain events are to take place at certain times. However, this course will consider only user-initiated events.
Event-driven programming represents an entirely different style of programming. All of the code that you have worked on so far has been fairly 'linear' in nature – it has been possible to plot a route through the code to show the order of execution. However, with event-driven programming this is no longer necessarily the case. Essentially, components are waiting around for an outside body – the user – to initiate an event through one of the visual components – clicking a button, for example. But you, the programmer, do not know when the button will be pressed, whether a number of buttons will be pressed, or in which order the user will press them.
You will see that a major part of event-driven programming is the creation of objects called listeners that are attached to components. As their name suggests they 'listen' for events happening to 'their' components. These listeners then 'fire' off the desired code. Listeners can be 'told' to look at particular components and to look only at particular events. For example, a listener may be interested only in a mouse entering a particular part of the screen and not in it being clicked.
We will also continue with the Calculator example started in the last unit. In this unit we show how the action of the user clicking on a button can be linked to the code that will carry out the actions and then display the result.