600 likes | 931 Views
JAVA GUI Interface. AWT. Abstract Window Toolkit - Java 1 SWING – Java 2 enhancements Classes and other tools for building programs that have a graphical user interface. “Abstract” refers to the AWT’s ability to run on multiple platforms.
E N D
AWT • Abstract Window Toolkit - Java 1 • SWING – Java 2 enhancements • Classes and other tools for building programs that have a graphical user interface. • “Abstract” refers to the AWT’s ability to run on multiple platforms. • Building a GUI involves creating “abstract” components such as buttons and windows, which are then mapped to “concrete” components for a specific platform.
Swing • Java 2 • More powerful than AWT • Used to build graphical user interfaces • Swing is built around the existing AWT • Swing is very similar to the AWT • Many Swing classes correspond to AWT classes. • Swing’s JButton class corresponds to the AWT’s Button class.
Creating a Graphical User Interface • GUI programming in Java is based on three concepts: • Components. • A component is an object that the user can see on the screen and—in most cases—interact with. • For example -- a command button, a label, a textfield • Containers. • A container is a component that can hold other components. Example: a frame or a panel • Events. • An event is an action triggered by the user, such as a key press or mouse click.
Designing a Graphical User Interface • Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events.
Creating a Graphical User Interface • Components are objects, so they’re created by invoking a constructor. • A button would be created by using a constructor belonging to the JButton class. • The most commonly used constructor has one argument (the button’s label): JButton b = new JButton("Testing"); • For a component to be visible, it must be added to a container (typically a frame) by the add method.
Creating a Graphical User Interface • To detect when an event occurs, a special “listener” object can be attached to a component. • When the user performs an action that involves the component, a method belonging to the listener object will be called automatically.
Frames • In Java terminology, a frame is a window with a title and a border. • A frame may also have a menu bar. • Frames play an important role in the AWT because a GUI program normally displays a frame when it’s executed.
The JFrame Class • Frames are created using one of the constructors in the Frame class. • One constructor takes a single argument (the title to be displayed at the top of the frame): JFrame f = new JFrame("Title goes here"); • By default, the frame object is invisible • Before making the frame visible, a method should be called to set the size of the frame. • If desired, the frame’s location can also be specified.
Frame Methods • Many methods used with Frame objects are inherited from Window (Frame’s superclass) or from Component (Window’s superclass). • The setSize method sets the width and height of a frame: f.setSize(width, height); • If a program fails to call setSize before displaying a frame, it will assume a default size.
Frame Methods • The setVisible method controls whether or not a frame is currently visible on the screen. • Calling setVisible with true as the argument makes a frame visible: f.setVisible(true); • Calling it with false as the argument will make the frame disappear from the screen: f.setVisible(false); • The Frame object still exists; it can be made to reappear later by calling setVisible again.
Creating a Frame • The FrameTest program creates a Frame object and displays it on the screen. • This program illustrates three key steps: • Using the Frame constructor to create a frame. • Setting the size of the frame. • Displaying the frame on the screen.
FrameTest.java // Displays a frame on the screen. // WARNING: Frame cannot be closed. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class FrameTest { public static void main(String[] args) { JFrame f = new JFrame("Frame Test"); f.setSize(150, 100); f.setVisible(true); } }
Creating a Frame • Frame created by the FrameTest program:
Creating a Frame • Clicking on the Close button has no effect, because there’s no action associated with that button. • The frame will have be closed the hard way, by killing the program -- ctl/alt/del
Setting the Location of a Frame • By default, all windows (including frames) are displayed in the upper-left corner of the screen, which has coordinates (0, 0). • The setLocation method can be used to specify a different location: f.setLocation(50, 75); • To find the current location of a frame, call getLocation: Point frameLocation = f.getLocation(); The coordinates of f’s upper-left corner will be stored in frameLocation.x and frameLocation.y.
Adding Components to a Frame • The Frame class is rarely used to create objects directly. • Define a subclass of Frame and then create an instance of the subclass. • This makes it possible to tailor the subclass. • The constructor for the subclass can put components into the frame. It will call the frame constructor.
Adding Components to a Frame • To add a component to a frame (or any kind of container), the add method is used. • An example of adding a button to a frame: JButton b = new JButton("Testing"); add(b); • These statements would normally go in the constructor for the subclass of the frame.
Adding Components to a Frame • ButtonTest defines a subclass of Frame named ButtonTestFrame, and then creates an instance of ButtonTestFrame. • Notes: the “extends” implies subclass • Actions taken by the ButtonTestFrame constructor: • Invokes the superclass (the Frame)constructor, passing it the title of the frame. • Calls setLayout to specify how the components inside the frame will be laid out. • Creates a Button object. • Calls add to add the button to the frame.
ButtonTest.java // WARNING: Frame cannot be closed. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ButtonTest { public static void main(String[] args) { JFrame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); } } // Frame class class ButtonTestFrame extends JFrame { public ButtonTestFrame(String title) { super(title); getContentPane().setLayout(new FlowLayout()); Button b = new Button("Testing"); getContentPane().add(b); } }
Adding Components to a Frame • Frame created by the ButtonTest program: • Pressing the “Testing” button has no effect.
Adding Components to a Frame • Instead of calling setSize, the main method in ButtonTest could have called pack: f.pack(); • pack makes the frame just large enough to display the components within it:
Adding Components to a Frame • Instead of calling setSize, the main method in ButtonTest could have called pack: f.pack(); • pack makes the frame just large enough to display the components within it: • Regardless of whether setSize or pack is called, the user can manually resize the frame.
Adding Components to a Frame • It’s not necessary to have two separate classes, (ButtonTest and ButtonTestFrame). • By moving the main method from ButtonTest to ButtonTestFrame, the program could be condensed to one class (ButtonTestFrame).
Event Listeners • When the user performs an action, Java creates an object containing information about the event. • Responding to an event is done by writing a method that can be called when the event occurs.
Event Listeners • Steps involved in handling an event: • The user performs an action, causing an event to be triggered • A listener object is created that contains information about the event, including an indication of which component was involved. • A method that belongs to a listener object is called. The object created in step 2 is passed to the method.
Interfaces • Event-handling requires the use of interfaces. • An interface looks like a class, except that its methods aren’t fully defined. • Each method in an interface has a name, a parameter list, and a result type, but no body. • One common interface is named ActionListener: public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent evt); } • The code above shows how ActionListener is defined in the interface. • This resembles a class declaration, except that the word class has been replaced by interface, and the actionPerformed method has no body.
Interfaces • An interface is nothing but a pattern that will be used later to define “real” classes. • A class implements an interface by agreeing to provide bodies for all methods in the interface. • A class that implements the ActionListener interface would have to provide a method named actionPerformed with one parameter of type ActionEvent and a result type of void.
Interfaces • The keyword implements is used to tell the compiler that a class will implement a particular interface. • A class that implements the ActionListener interface: class class-name implements ActionListener { public void actionPerformed(ActionEvent evt) { … } … // Variables, constructors, and methods, // if desired }
Creating Event Listeners • To handle an event, it’s necessary to create an event listener object. • This object will be “registered” with a component; when an event occurs that involves the component, one of the listener’s methods will be called. • An event listener will be an instance of a “listener class” defined by the programmer.
Creating Event Listeners • Pressing a button is an action event, so the listener class for a button would need to implement the ActionListener interface. • To implement this interface, the class must define a publicvoid method named actionPerformed with a parameter of type ActionEvent.
Creating Event Listeners • An example of a listener for an action event: class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { … } }
Creating Event Listeners • After writing a listener class, the next step is to create an instance of the class and connect it to a particular component. • In the simplest case, a single listener object will be attached to a single component.
Creating Event Listeners • Suppose that b is a Button object: JButton b = new JButton("Change Color"); • A listener object can be created by using the constructor for the listener class: ButtonListener listener = new ButtonListener(); • listener can now be registered as an action listener for the button: b.addActionListener(listener); • It’s sometimes possible to save a statement by combining the creation of the listener object with the call of addActionListener: b.addActionListener(new ButtonListener());
ButtonTest2.java // Displays a frame containing a single ”Close // Window” Button. The frame/window is closed // when the button is pressed import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ButtonTest2 { public static void main(String[] args) { JFrame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); } }
// Frame class class ButtonTestFrame extends JFrame { public ButtonTestFrame(String title) { super(title); getContentPane(). setLayout(new FlowLayout()); Button b = new Button(“Close Window”); getContentPane().add(b); b.addActionListener(new ButtonListener()); } } // Listener for button class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { System.exit(0); } }
Creating Event Listeners • Frame created by the ButtonTest2 program:
Creating Event Listeners • Pressing the “Close window” button causes a call of the actionPerformed method for the button’s listener object. • This method calls System.exit, which causes the program to terminate and the frame to disappear. • When a program terminates, any windows that it created are automatically closed.
Creating Event Listeners • There’s a similar set of listener interfaces for the Window Events • Such as clicking on the X in the upper right hand corner • The listener interface for WindowEvent is named WindowListener. • But the WindowListener has SEVEN required methods (not just one -- as in the action listener)
Adapter Classes • To make the Close button work, a WindowEvent listener is needed. • A class that implements the WindowListener interface would have to contain seven methods.
Adapter Classes • There’s an easier technique: use the WindowAdapter class from the javax.swing or java.awt.event package. • This class implements the WindowListener interface, although the methods that it provides are all empty. • An Adapter class is a class that implements a Listener. All methods are written as empty methods. The programmer only needs to write the methods he/she needs. • With an Interface, all methods must be written.
Adapter Classes • The user-written listener class will extend the WindowAdapter class and override the windowClosing method. • It will then inherit all the other methods it needs. • WindowAdapter is an example of an adapter class—a class that can be extended instead of implementing an interface. • Java provides matching adapter classes for most interfaces that have two or more methods.
Adapter Classes • The ButtonTest3 program is a modification of ButtonTest2. • The new WindowCloser class extends WindowAdapter and provides a windowClosing method of its own. • The constructor for ButtonTestFrame now calls addWindowListener to install a WindowCloser object as a listener for window events.
ButtonTest3.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing either the // "Close window" button or the frame's "close" button. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ButtonTest3 { public static void main(String[] args) { JFrame f = new ButtonTestFrame("Button Test"); f.setSize(150, 100); f.setVisible(true); } }
// Frame class class ButtonTestFrame extends JFrame { public ButtonTestFrame(String title) { super(title); getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Close window"); getContentPane().add(b); b.addActionListener(new ButtonListener()); addWindowListener(new WindowCloser());// Attach listener } } // Listener for button class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent evt) { System.exit(0); } }
// Listener for window class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent evt) { System.exit(0); } }
Adapter Classes • When a window event occurs, one of the methods in the WindowCloser class will be called. • If the event is caused by the user attempting to close the window, the windowClosing method is called, and the program terminates. • Any other window event will cause one of WindowCloser’s inherited methods to be called. • These methods are empty, so nothing will happen.
Inner Classes • The ChangeColor program will also have a single button. • Pressing the button will change the background color of the frame. The background will initially be white:
The ChangeColor Program • Pressing the button once will change the background to black: • Pressing it again will cause the background to return to white.