JComponent Manipulation | |||||||||||||||||
|
ActionListeners | |
The basic event model of Swing is that when an event happens
(such as a user clicking on a button) an ActionEvent is sent to the button
in question. In order to be aware of this event (sometimes termed catching the
event), we have to an ActionListener class attached to the button.
ActionListener is a simple Interface:
public interface ActionListener extends EventListener { void actionPerformed(ActionEvent e); }So basic ActionListener would be: public class DebugActionListener implements ActionListener { void actionPerformed(ActionEvent e) { System.out.println("Event Performed:\n" + e.toString()); } }DebugActionListener.java Once we have an ActionListener, we then just just attached it to one or more JComponents: JButton button = new JButton("Click Me1"); button.addActionListener(new DebugActionListener());Source code Notice there is a lot of information in an ActionEvent, a handy method is .getSource() which gives the Object which was the source of the Event. |
The Observer Pattern | |
Java provides an implementation of this pattern with
Observer and
Observable
Example:
Jarfile of Example Notice how this model not only allows the GUI to update itself whenever the data changes, but it doesn't require an ActionListeners |
Quick and Dirty Dialog Boxes | |
To pop up a dialog box with an acknowledge button:
JOptionPane.showMessageDialog(parent, String); Where parent is the JFrame that is popping up the dialog and String is the message you want to display. |
Exercise |
|
Add an ActionListener to the GUI you wrote last week so that when a user clicks on the
Compute button, it performs the calculation and displays the result. Emulate the behavior
in SimpleApplication5.class basically.
Feel free to SimpleApplication3.java if you had difficult getting a reasonable window layout. In addition, modify the code provided for the Observer Pattern so that in addition to displaying the current matrix values, it displays the sum of the matrix.
For Monday, Due Wednesday 5PM |