public void actionPerformed(ActionEvent e) { JButton jb; jb = (JButton)e.getSource(); if (jb == myButton) ... }
Key Events
To capture key events, set a KeyListener which implements:
public void keyPressed(KeyEvent e); public void keyReleased(KeyEvent e); public void keyTyped(KeyEvent e);You must also execute:
Mouse Events
There are two groups of mouse events:
MouseEvent and MouseMotionEvent.
You can add a listener to any Component, e.g.
JPanel jp = new JPanel(); jp.addMouseLisener(xxx); jp.addMouseMotionListener(xxx);A MouseListener must implement:
public void mouseClicked(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e);Often you only need one of these, say mousePressed.
Alternatively, you can just extend mouseAdapter which is a class that has these 5 functions with empty bodies. Just override the ones you want to use.
This alone is not useful since a class can extend only one other class
This is weher inner classes come in.
Make an inner class that extends mouseAdpater can override just
the mousePressed method. The inner class has access to all of the
private methods of its outer class.
See the Mouse2 example.
The MouseMotionListener must implement:
public void mouseMoved(MouseEvent e); public void mouseDragged(MouseEvent e);
The MouseInputListener (part of swing, not awt)
is a third kind of mouse listener that combines the two.
See the Mouse3 example.