Java Reference
In-Depth Information
instance, the user clicks on a button, closes a window, resizes a window, selects an item in a combo-
box, or even moves the mouse around inside a window.
When building console programs, there is a set sequence of actions, and the program will stop
execution when it expects input from the user, and continues onward once it has received it. In
graphical programs, the user can at any time do a number of things: type in a textbox, minimize a
window, or click a button. All these actions by the user are called “events.” Not only in Java, but in
many other programming languages, there is usually an “event loop,” which is a background task
that constantly checks for any new event and responds accordingly. This type of program is said to
be event‐driven. In Java, you do not have to deal with this event loop directly, but you can plug into
it so you can capture interesting events (a user clicked a button) and deal with them accordingly.
This is done by creating so‐called event listeners.
Note Some programming languages make the concept of an “event loop”
a core architectural construct. Node.js , for instance, has become popular as
a JavaScript‐based (not Java) programming framework that applies an event
loop to the whole program, not just to the GUI.
event listeners
You've already learned that any user action within a GUI application will lead to some kind of
event. By default, all of these events just happen, but to make useful applications, you'll need to
define event listeners. These are objects that can receive a notification when a specific event of inter-
est has happened. This is illustrated in the following Try It Out example.
Creating a BMI Calculator
try it out
In this Try It Out, you create a graphical Body Mass Index (BMI) calculator.
1.
As always, feel free to create a new project in Eclipse when you want to. Create a class called
BMICalculator with the following content:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BMICalculator extends JFrame {
private final JTextField txtMass = new JTextField();
private final JTextField txtHeight = new JTextField();
private final JButton btnCalc = new JButton("Calculate BMI");
 
Search WWH ::




Custom Search