CH6-GUI & Java Applets
CH6-GUI & Java Applets
Chapter six
GUI & Java Applets
• A container is a type of component that has the purpose of containing other components.
• Types of containers:
• Top-level containers: Every Swing program contains at least one top-level container (e.g. JFrame,
JDialog or JApplet). Top-level containers cannot be added to other containers.
• Intermediate containers: used to group components so that they can be handled as a single component
(e.g JPanel, JTabbedPane).
• Atomic components (basic controls): cannot contain other components (e.g JButton, JTextField).
The Swing Class Hierarchy
Description of Classes
• Object: All classes ultimately derive from Object, thus this class is at
the top of the tree.
• Frame: a type of Window that serves as the basis for Java GUI
applications. Frame is an AWT class that has been improved upon by the
JFrame class.
• JFrame: the Swing version of the older Frame class. Most of the Swing
applications include at least one JFrame object.
• JComponent: is the basis for all other Swing components except for
frames.
Description of Classes (Cont’d)
f.setVisible(true);
}
}
Using Swing Components
• Very simple, just create object from appropriate class – examples:
• JButton but = new JButton();
• JTextField text = new JTextField();
• JTextArea text = new JTextArea();
• JLabel lab = new JLabel();
• Many more classes. Don’t need to know every one to get started.
Adding Components to a Frame
• A JFrame has several areas
• Window decorations
• (Optional) Menu bar
• Content pane
• Content pane is where components are added.
• Content pane is a Container object
• Obtain reference to the content pane, and then add another component to it
JFrame frame = new JFrame(“Example”);
JButton button = new JButton(“Click me!”);
frame.getContentPane().add( button );
Adding Components
• Very common to extend the Swing components, particularly JFrame
• Create your own specialised versions
• May include a fixed set of components
• Provide extra methods for working with those components, etc.
• Encapsulates how the GUI is constructed
• Slightly different to Visual Basic where one tends to just use the basic
components
Layout Managers
• Responsible for layout out (arranging) components in a Container
• Several different types with different uses
• None of them provide for precise x-y alignment, unlike VB forms
Border Layout
• This is the default layout for JFrame
• Divides the content pane into 5 areas (north, south, east, west, center)
• Areas are expanded/contracted as needed, along with their contents.
• Therefore ignores preferred size of the components.
• Center is the default if not specified.
• Adding two components to the same zone means they get added one
on top of the other
• Instead add the components to a JPanel, and then add that instead.
Border Layout
X
NORTH
SOUTH
Example
import javax.swing.*;
import java.awt.BorderLayout;
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
24
Menus
• A Jframe can have only a single menu bar
• Instance of the Jmenu object
• A menu bar can have several menus on it
• Instances of the Jmenu object
• A menu can have several items on it
• Instances of the JmenuItem object
What are events?
• All components can listen for one or more events.
• Typical examples are:
• Mouse movements
• Mouse clicks
• Hitting any key
• Hitting return key
• etc.
• Telling the GUI what to do when a particular event occurs is the role
of the event handler.
Event Handling
• Every time the user types a character or pushes a mouse button, an event occurs. Any object can
be notified of the event. All it has to do is implement the appropriate interface and be registered
as an event listener on the appropriate event source. :
• Act that results in the event Listener type:
• User clicks a button, presses Return while typing in a text field, or chooses a menu item
ActionListener
• User closes a frame (main window) WindowListener
• User presses a mouse button while the cursor is over a component MouseListener
• User moves the mouse over a component MouseMotionListener
• Component becomes visible ComponentListener
• Component gets the keyboard focus FocusListener
• Table or list selection changes ListSelectionListener
ActionEvent
• In Java, most components have a special event called an ActionEvent.
• This is loosely speaking the most common or canonical event for that
component.
• A good example is a click for a button.
• To have any component listen for ActionEvents, you must register the
component with an ActionListener. e.g.
• button.addActionListener(new MyAL());
actionPerformed
• The actionPerformed method has the following signature:
void actionPerformed(ActionEvent)
• The object of type ActionEvent passed to the event handler is used to query
information about the event.
• Some common methods are:
• getSource()
• object reference to component generating event
• getActionCommand()
• some text associated with event (text on button, etc).
• These methods are particularly useful when using one eventhandler for multiple
components.
• When the action event occurs, that object's actionPerformed method is invoked.
Simplest GUI
import javax.swing.JFrame;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
show();
}
36
…What Are Applets?
37
… applet program
1. Sub class Applet class.
4. The code of the applet is downloaded when the user view the html page
contains applet.
38
Application vs. Applet
Application
Trusted (i.e., has full access to system resources)
Invoked by Java Virtual Machine (JVM, java), e.g.,
java HelloWorld
Should contain a main method, i.e.,
public static void main(String[])
Applet
Not trusted (i.e., has limited access to system resource to prevent security
breaches)
Invoked automatically by the web browser
Should be a subclass of class java.applet.Applet to be viewed in a web
browser.
provides a common interface so that a web browser can communicate with a applet
39
Applet class
Applet class extends java.awt.Panel.
This implies applet is a panel(container).
It is used to create the GUI.
Therefore to add components into applet add the component in to ways.
1. Add components directly to the applet.
2. Add component to the applet and later add the applet to the
container.
Note 1: to add panels or components to applet use
this.add(componentname/panelname);
Not 2 :To add component to the panel
panelname.add(componentname);
40
At the technical level,
• An applet is an object whose class descends ultimately from Applet or JApplet.
• An applet typically overrides the inherited init, start, stop, and paint methods.
42
Applet Summary
Applets are Java programs that can be embedded in Hypertext
Markup Language (HTML) documents.
When a browser loads a Web page containing an applet, the applet
downloads into the Web browser and executes.
Every Java applet is a graphical user interface on which you can place
GUI components or draw.
To enable an applet to draw, override its method paint.