1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class MyMouseListener implements MouseListener { 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) { } }
public class MyMouseMotionListener implements MouseMotionListener { public void mouseDragged(MouseEvent me) { } public void mouseMoved(MouseEvent me) { } }
public class MyKeyListener implements KeyListener { public void keyPressed(KeyEvent key) { } public void keyReleased(KeyEvent key) { } public void keyTyped(KeyEvent key) { } } |
You can of course combine them:
1 2 3
| public class MySuperAwesomeListener implements MouseListener, MouseMotionListener, KeyListener { .... } |
And you can also use an Adapter to only use certain methods you need:
1 2 3
| public class MyMouseListener extends MouseAdapter { } |
MouseListener -> MouseAdapter
MouseMotionListener -> MouseMotionAdapter
KeyListener -> KeyAdapter
Do note that Java is a single-inheritance language, which means a class can only extend 1 class but can implement as many interfaces as it wants.
To add a listener:
1 2 3 4
| JComponent component = new MyCustomJComponent(); component.addMouseListener(new MyMouseListener()); component.addMouseMotionListener(new MyMouseMotionListener()); component.addKeyListener(new MyKeyListener()); |
You can also use the anonymous inner class syntax to create quick listeners:
1 2 3 4 5 6
| component.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent key) { if(key.getKeyCode() == KeyEvent.VK_ENTER) System.out.println("YOU PRESSED ENTER!!"); } }); |
To load an image, you use the javax.imageio.ImageIO class:
1
| BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource("res/images/MyImage.png")); |
getResource(String) takes a path that is relative to the working directory, or the root, of the project. This means in Eclipse, the root is the "bin" folder. In a JAR file, the root is the root of the JAR file or the folder it's in.