Flashcards in Java
Written By: James Williams
- 10 Apr 2006 -
Description: By using Java and XML, this tutorial walks you through creating flashcards for learning French.
ActionListener/MouseListeners
We need a way to respond to the user when they select menu options. For that, we will use ActionListeners. ActionListeners run a function when an action is performed. There are two ways to implement ActionListeners, either implement ActionListener globally for the class or use anonymous classes.
public MyClass extends JFrame implements ActionListener { MyClass () { .... } public void actionPerformed(ActionEvent e) { if (e.getSource = loadList) //.... if (e.getSource() = prefs) // ... //.... } }
This solution is usually not a good idea because even with a small amount of components, the code would get messy with a bunch of if-statements. Anonymous interfaces/classes are much more compact. They are a way of deriving from a class or interface without giving it a name. Despite a slightly unique form, they are useful in making code more readable. It is basically defining and passing a whole class definition as a parameter. For example,
JButton ok = new JButton("Ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //do stuff } });
To further simplify, our ActionListeners will have each have a single call to a void function that takes no parameters except exit. Last but not least, we will need a JLabel to display the text. Since we need to alter the values from time to time, we need this to be a class instance variable. The JLabel responds needs to respond to mouse clicks to advance. If we use an anonymous MouseListener, we will have define all its functions even though we are only interested in mouseClicked.
interface MouseListener { abstract public void mouseClicked(MouseEvent e) {} abstract public void mouseEntered(MouseEvent e) {} abstract public void mouseExited(MouseEvent e) {} abstract public void mousePressed(MouseEvent e) {} abstract public void mouseReleased(MouseEvent e) {} }
To get around this requirement, we use a MouseAdapter, which is basically a MouseListener with all the functions declared with no contents so you can define only the one you want.
text.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { try { advance(); } catch (NullPointerException ne) { } } });