In 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 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 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 button1.addActionListener(lForButton); thePanel.add(button1); // How to add a text field ---------------------- textField1 = new JTextField("Type Here", 15); ListenForKeys lForKeys = new ListenForKeys(); textField1.addKeyListener(lForKeys); thePanel.add(textField1); // 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 textArea1.setLineWrap(true); // Makes sure that words stay intact if a line wrap occurs textArea1.setWrapStyleWord(true); // Adds scroll bars to the text area ---------- JScrollPane scrollbar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // Other options: VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_NEVER thePanel.add(scrollbar1); this.add(thePanel); ListenForWindow lForWindow = new ListenForWindow(); this.addWindowListener(lForWindow); this.setVisible(true); // Track the mouse if it is inside of the panel ListenForMouse lForMouse = new ListenForMouse(); thePanel.addMouseListener(lForMouse); } // 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){ buttonClicked++; // 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"); } } }
wowww, just waiting for your new video, will watch it today…
thank you….
You’re very welcome. It’s a tutorial packed with information
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.
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..
Your in luck. I’ve already covered that topic using PHP. Every technique is nearly identical using Java
PHP Security
PHP Security Pt 2
PHP Security Pt 3
PHP Security Pt 4 Set Up Captcha
PHP Security Pt 5 SQL Injection
PHP Security Pt 6 Directory Traversal
Web Design and Programming Pt 21 Secure Login Script
Well my good luck works for me..;-)
but the functions you are using are for php, how do i use them in java??
Most of what I do is test data using regular expressions. It should be easy to just use those same codes since regex are identical. I’ll cover sessions, cookies, databases as soon as possible. It’s getting harder to cover the more complicated topics quickly
okay…thanks…
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.
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?
hi derek, thanks for the video man, i just had one question.
=>what is the difference between keyPressed and Keytyped method.
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
hi derek, can u tell me what is the difference between keytyped and keypressed
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
Hey Derek, what is a FocusListener meant to do?
Sorry, I wasn’t patient enough. I understand it now :).
Sorry I couldn’t get to you quicker, but I’m glad you understand now 🙂
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.
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.
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.
Thx
Sure feel free to bounce around in the tutorial however you’d like.
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.
Thanks
Kuldeep
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
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!
I will definitely be covering how to connect Android apps to remote servers very soon. I’m very happy that you enjoy the videos. Many more are coming 🙂
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.
Hi Wang, Thank you very much for taking the time to tell me that I’ve helped. I greatly appreciate that! I wish you and your friends all of the best 🙂
Hi Derek!
Still havent’s figured out what FocusListened does… Could you please give some expanation?
Thanks
A focus listener is triggered anytime a component is targeted by mouse, the keyboard, or programmatically