Java Video Tutorial 21

Java Swing Event HandlingIn this part of my Java Video Tutorial, I will cover GUI Event Handling. If you missed my Java Swing video tutorial, watch that first.

Here I show you how to implement the ActionListener, KeyListener, MouseListener and WindowListener. I also show you some easy ways to use interfaces so that you don’t have to memorize all of the required methods for each interface.

All of the code follows the video. Definitely look at it so that you will find it easier to learn.

If you like videos like this share it

Code from the Video

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;

import java.awt.event.*;

// Extends JFrame so it can create frames

public class LessonTwentyOne extends JFrame{
	JButton button1;
	JTextField textField1;
	JTextArea textArea1;
	int buttonClicked;
	public static void main(String[] args){
		new LessonTwentyOne();
	public LessonTwentyOne(){
		// Define the size of the frame
		this.setSize(400, 400);
		// Toolkit is the super class for the Abstract Window Toolkit
		// It allows us to ask questions of the OS
		Toolkit tk = Toolkit.getDefaultToolkit();
		// A Dimension can hold the width and height of a component
		// getScreenSize returns the size of the screen
		Dimension dim = tk.getScreenSize();
		// dim.width returns the width of the screen
		// this.getWidth returns the width of the frame you are making
		int xPos = (dim.width / 2) - (this.getWidth() / 2);
		int yPos = (dim.height / 2) - (this.getHeight() / 2);
		// You could also define the x, y position of the frame
		this.setLocation(xPos, yPos);
		// Define how the frame exits (Click the Close Button)
		// Without this Java will eventually close the app
		// Define the title for the frame
		this.setTitle("My First Frame");
		// The JPanel contains all of the components for your frame
		JPanel thePanel = new JPanel();
		// Create a button with Click Here on it
		button1 = new JButton("Click Here");
		// Create an instance of ListenForEvents to handle events
		ListenForButton lForButton = new ListenForButton();
		// Tell Java that you want to be alerted when an event
		// occurs on the button
		// How to add a text field ----------------------
		textField1 = new JTextField("Type Here", 15);
		ListenForKeys lForKeys = new ListenForKeys();
		// How to add a text area ----------------------
		textArea1 = new JTextArea(15, 20);
		// Set the default text for the text area
		textArea1.setText("Tracking Events\n");
		// If text doesn't fit on a line, jump to the next
		// Makes sure that words stay intact if a line wrap occurs
		// Adds scroll bars to the text area ----------
		JScrollPane scrollbar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		ListenForWindow lForWindow = new ListenForWindow();
		// Track the mouse if it is inside of the panel
		ListenForMouse lForMouse = new ListenForMouse();
	// Implements ActionListener so it can react to events on components
	private class ListenForButton implements ActionListener{
	// This method is called when an event occurs
	public void actionPerformed(ActionEvent e){
		// Check if the source of the event was the button
		if(e.getSource() == button1){
			// Change the text for the label
			textArea1.append("Button clicked " + buttonClicked + " times\n" );
			// e.getSource().toString() returns information on the button
			// and the event that occurred
	// By using KeyListener you can track keys on the keyboard
	private class ListenForKeys implements KeyListener{
		// Handle the key typed event from the text field.
	    public void keyTyped(KeyEvent e) {
	    	textArea1.append("Key Hit: " + e.getKeyChar() + "\n"); 

	    // Handle the key-pressed event from the text field.
	    public void keyPressed(KeyEvent e) {

	    // Handle the key-released event from the text field.
	    public void keyReleased(KeyEvent e) {
	private class ListenForMouse implements MouseListener{

		// Called when a mouse button is clicked
		public void mouseClicked(MouseEvent e) {
			textArea1.append("Mouse Panel Pos: " + e.getX() + " " + e.getY() + "\n");
			textArea1.append("Mouse Screen Pos: " + e.getXOnScreen() + " " + e.getYOnScreen() + "\n"); 
			textArea1.append("Mouse Button: " + e.getButton()  + "\n"); 
			textArea1.append("Mouse Clicks: " + e.getClickCount()  + "\n");

		// Called when the mouse enters the component assigned
		// the MouseListener
		public void mouseEntered(MouseEvent arg0) {
			// TODO Auto-generated method stub

		// Called when the mouse leaves the component assigned
		// the MouseListener
		public void mouseExited(MouseEvent arg0) {
			// TODO Auto-generated method stub

		// Mouse button pressed
		public void mousePressed(MouseEvent arg0) {
			// TODO Auto-generated method stub

		// Mouse button released
		public void mouseReleased(MouseEvent arg0) {
			// TODO Auto-generated method stub
	private class ListenForWindow implements WindowListener{

		// Called when window is the active window
		public void windowActivated(WindowEvent e) {
			textArea1.append("Window Activated\n");

		// Called when window is closed using dispose
		// this.dispose(); can be used to close a window
		public void windowClosed(WindowEvent arg0) {
			// TODO Auto-generated method stub

		// Called when the window is closed from the menu
		public void windowClosing(WindowEvent arg0) {
			// TODO Auto-generated method stub

		// Called when a window is no longer the active window
		public void windowDeactivated(WindowEvent e) {
			textArea1.append("Window Activated\n");

		// Called when the window goes from minimized to a normal state
		public void windowDeiconified(WindowEvent arg0) {
			textArea1.append("Window in Normal State\n");

		// Called when the window goes from normal to a minimized state
		public void windowIconified(WindowEvent arg0) {
			textArea1.append("Window Minimized\n");

		// Called when the window is first created
		public void windowOpened(WindowEvent arg0) {
			textArea1.append("Window Created\n");

29 Responses to “Java Video Tutorial 21”

  1. punit says:

    wowww, just waiting for your new video, will watch it today…
    thank you….

  2. punit says:

    if possible add some security concerns for web development in java(ie. how to secure from sql injuctions, cross site scripting, how to set up https in tomcat) etc, to make a website secure, like an e-commerce site.

  3. punit says:

    if possible please, do some tutorial for java securities in web devlopement(ie. how to secure site from sql injuctions, cross site scripting, how to setup https in tomcat)etc. like useful for some e-commerce sites..

  4. Aamir says:

    hi derek i have few questions regarding this tutorial
    1.)when we create an object like ListenForButton lForButton then why do we have to pass it like button1.addActionListner(lForButton);
    2.)why do we create private class abc implements def, can’t we do it by defining a function.plz explain. also tell me if a class is defined into another class does it gets all of the fields and methods of the parent class under which it is enclosed.

    • Derek Banas says:

      button1.addActionListener(lForButton); says that when an event is triggered on button1 that you want the class ListenForButton to be called. Then the method actionPerformed is called and it handles what to do when an event is triggered.

      If a class extends another class yes the new class gets all of the methods of the super class.

      Does that help?

  5. Lucky says:

    hi derek, thanks for the video man, i just had one question.

    =>what is the difference between keyPressed and Keytyped method.

    • Derek Banas says:

      keyPressed – when the key goes down
      keyReleased – when the key comes up
      keyTyped – when the unicode character represented by this key is sent by the keyboard to system input

  6. Aamir says:

    hi derek, can u tell me what is the difference between keytyped and keypressed

    • Derek Banas says:

      keyPressed – when the key goes down
      keyReleased – when the key comes up
      keyTyped – when the unicode character represented by this key is sent by the keyboard to system input

  7. Samuel Pius says:

    Hey Derek, what is a FocusListener meant to do?

  8. Samuel Pius says:

    Sorry, I wasn’t patient enough. I understand it now :).

  9. Dude says:

    Hey Derek,

    Awesome Videos, even though i have a couple of problems with this episode and especially with actionlisteners:

    I am using Netbeans, and even if i copy and paste your code, it gives me a lot of warnings and errors. If i write my own program, which is slightly different from yours, i end up getting errors when i try to implement “private class ListenForButton implements ActionListener{}” for instance. It says it is not abstract and cant override some other method.

    • Derek Banas says:

      That is odd. I also had some weird errors when I used NetBeans in the past and that is why I stuck with Eclipse. I’m using regular old Java in these tutorials so they should work on every IDE.

      Don’t worry about understanding Action Listeners at this point. I cover them a countless number of times over the course of this tutorial. You’ll understand them with a few more examples.

  10. Anonymous says:

    Hi derek nice tutorials.One question, can i skip the swing tutorials, because later i will learn javafx and i want to continue with the thrid part of the tutorials. Can i continue without the swing tutorials.

  11. kuldeep says:

    Hi Derek,

    In video you put the code in KeyPressed function but in the code here it is given in KeyTyped method. Moreover, I am a bit unclear between the usage of KeyTyped and KeyPressed.


    • Derek Banas says:

      Hi Kuldeep,

      keyPressed – when the key goes down
      keyReleased – when the key comes up
      keyTyped – when the unicode character represented by this key is sent by the keyboard to system input

      • Danster says:

        I have implemented the focus listener and have found may uses for it :), although many, in my mind anyway are web related. Also Happy New Year! Love your videos and keep up the high quality content you produce!

  12. Wang says:

    Hi, Derek. I have to thank you for your work to help the programmers around the world. I’m from China and I have recommended my friends to watch your videos if they want to study how to program. Thank you so much.

  13. Alex_M says:

    Hi Derek!

    Still havent’s figured out what FocusListened does… Could you please give some expanation?


Leave a Reply

Your email address will not be published.