Head First Java: Chapter-12 summary
A Very Graphic Story
There are Command Line Interfaces (CLI) and Graphical User Interfaces (GUI). Java applications can be created for them. Users more interact with GUIs because it has colour buttons and text fields. So it is user-friendly. In this chapter, we are looking to create a GUI application with the Java Swing library.
A JFrame is the object that represents a window on the screen. The view of the JFrame will be different depending on the operating system. The J frame can have buttons, checkboxes, text fields, etc.
Create a button on the J frame and set text to its name.
Add the widget to the frame
We can’t add widgets directly to the JFrame because It’s a window. We add a thing to the JFrame content pane. And to set the window (JFrame) size and display it on the screen.
Example:
If we click the button, nothing will happen. Because we still do not assign the click event to the button.
Event Handling
Event Handling is used to handle different events. Like, click event handle what should happen when the button is clicked. So we must become familiar with the Listener interface to handle events.
A listener interface bridges the listener (you) and the event source (the button). There are lots of events like ActionEvent, MouseEvent, KeyEvent, etc. Every event type has a matching listener interface. All the ActionListeners are in the Java.awt package. So we must import this package before use. For Example, for the ActionEvent, there is an interface called ActionListener.Every event listener can have different methods to perform various actions for the same event. For Example, MouseListener has methods like mouseClick, mousePressed, and mouseReleased. But, ActionListener has only one method called actionPerformed. And the event is an object itself.
Making drawing widgets
As an above example, buttons and text fields can be added to the JFrame. Also, we can add 2D graphic objects to the JFrame.
Create a class named GrawPnel and extends it with JPanel class. Next, override the paintComponent() method.
Likewise, we can create GUI applications.