Page 705 - Introduction to Programming with Java: A Problem Solving Approach
P. 705

                16.14 Distinguishing Between Multiple Events 671 16.14 Distinguishing Between Multiple Events
Now that you understand the basic building blocks of GUI programming (JFrame and JOptionPane windows; JLabel, JTextField, and JButton components), you’re prepared to consider more complex situations that GUI programmers encounter. In this section, you’ll learn how to use a single listener to dis- tinguish between two different component events.
The getSource Method
Suppose you register a listener with two components. When the listener hears an event, you’ll probably want to determine which component fired the event. That way, you can customize your event handling: Do one thing if component X fired the event, and do another thing if component Y fired the event.
From within a listener, how can you determine the source of an event? In other words, how can you identify the component that fired an event? Call getSource, of course! More specifically, within the actionPerformed method, use the actionPerformed method’s ActionEvent parameter to call getSource. The getSource method returns a reference to the component whose event was fired. To see which component that was, use == to compare the returned value with the components in question. For example, in the below code fragment, we compare the returned value to a button component named okButton.
 public void actionPerformed(ActionEvent e)
{
          Apago PDF Enhancer
if (e.getSource() == okButton)
{
...
Improved FactorialButton Program
Remember the FactorialButton program from Figure 16.8? It calculated the factorial of a user-entered num- ber. The calculations were triggered by the user clicking the factorial button or the user pressing Enter in the input text box. With our simple first-cut FactorialButton program, we didn’t bother to distinguish be- tween the button-click event and the text-box-enter event. Let’s now improve the program by having the dif- ferent events trigger different results. The button click will still display the factorial, but the text box enter will display this dialog-box message:
See Figure 16.12. It shows the Listener class for our new and improved FactorialButton program. We’re only showing the Listener class because the rest of the program hasn’t changed. If you want to see the rest of the program, refer back to Figure 16.8. In our new Listener class, note how we call getSource and compare its returned value to xBox. xBox is the text box component that holds the user’s entry for x. If getSource returns xBox, we call showMessageDialog and display the above dialog- box message.
 




















































































   703   704   705   706   707