0% found this document useful (0 votes)
72 views41 pages

CH6-GUI & Java Applets

This document provides an overview of GUI and Java Applets. It discusses the key components of Swing for building GUIs, including common classes like JButton, JTextField. It also covers layout managers, events, menus and how to add components and handle events. The goal is for readers to understand how to write simple graphical user interfaces in Java using the Swing toolkit.

Uploaded by

melkamu tesfay
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
72 views41 pages

CH6-GUI & Java Applets

This document provides an overview of GUI and Java Applets. It discusses the key components of Swing for building GUIs, including common classes like JButton, JTextField. It also covers layout managers, events, menus and how to add components and handle events. The goal is for readers to understand how to write simple graphical user interfaces in Java using the Swing toolkit.

Uploaded by

melkamu tesfay
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 41

Course: Oop in Java Programing

Chapter six
GUI & Java Applets

Prepared By: Berhanu Anbase (MSC)


Objectives
- At the end of this chapter, you should be able to do the following:

• write a simple graphical user interface in Java using Swing;


• find out how to use components by browsing the Swing Tutorial and the Java
API;
• program listeners to respond to user generated events;
• use layout managers to arrange components attractively in windows
Introduction
• Up till now you have written programs that communicate with the
end user through a text-based interface
• Using System.out for output
• Using Keyboard for input.

• Java provides two sets of facilities for developing GUIs:


• The Abstract Window Toolkit (AWT): package java.awt
• Swing: package javax.swing
Java AWT
• Abstract Windowing Toolkit
• Original Java GUI API
• Very limited in capability
• Few components
• API not well structured, particularly event handling for user actions
• Not entirely portable (used native widgets)
Java Foundation Classes /Swing
• JFC(or “Swing”)
• Replacement for AWT (although does share some classes)
• Also provide basis for developing new GUI features (which are being
continually added)
• What does Swing include?
• 100% Java
• Swing components (more, and more sophisticated)
• Pluggable Look and Feel Support
• Accessibility API
• Better graphics support (Java 2D)
• Drag and Drop
What Swing is ?
• Swing is a package that lets you create applications that use a
flashy Graphical User Interface (or GUI) instead of a dull console
interface.
• The Swing API provides many different classes for creating
various types of user interface elements.
• Commonly used classes in javax.swing package:
• JButton, JTextBox, JTextArea, JPanel, JFrame, JMenu, JSlider, JLabel,
JIcon, …
• There are many, many such classes to do anything imaginable with
GUIs
JFC/Swing
• Disadvantages
• Can be slow (resource hungry)
• Large complex API (big learning curve)
• Many features best suited for GUI builders, IDEs
• Important to use Swing and not AWT
• Swing is the recommended way to build Java GUIs
GUI
A GUI gives an application a distinctive “look” and “feel”.
• A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
• GUI: a program that users visually sees and interact with.
• GUIs are built from GUI components.
• A GUI component is an object with which the user
interacts via the mouse, the keyboard or another form of
input, such as voice recognition.
Components and containers

• A component is any GUI element, such as a window, button or label.

• 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.

• Component: represents an object that has a visual representation


that can be shown on-screen and that can interact with users. This
class defines some basic methods that are available to all Swing
classes.
Description of Classes (Cont’d)

• Container: builds on the basic visual capabilities of the Component


class by adding the ability to hold other containers.

• Window: a specialized type of container object that has a border, a


title bar, buttons that minimize, maximize, and close the window, and
that can be repositioned and possibly even resized by the user.
Description of Classes (Cont’d)

• 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)

• JPanel: used to organize and control the layout of other components


such as labels, buttons, text fields, etc. In most Swing applications,
one or more panels are added to a frame. Then, when the frame is
displayed, the components that were added to its panels are made
visible.

• JLabel: creates a label that displays a simple text value.


Swing Top level containers
• JWindow
• Basic no frills window, just a square on the screen
• JFrame
• The basic Swing window. Offers basic window controls, resizable
• JDialog
• For building dialog boxes, e.g. File open/save
• JApplet
• For building applets, embedded into a web page
Working with JFrames
• Many different possibilities, but the basics include:
• Setting window title
• Setting location on screen
• Setting size of window
• Restricting resizes
• Set close operation (exit the program), as by default it does nothing.
A first Swing application
import javax.swing.*;
public class FirstGUI
{
public static void main(String[] args)
{
JFrame f = new JFrame();

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

WEST CENTER EAST

SOUTH
Example
import javax.swing.*;
import java.awt.BorderLayout;

public class First {


public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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();
}

public static void main(String[] args){


SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}
}
Another Simple GUI
import javax.swing.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.add(but1);
show();
}

public static void main(String[] args){


SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
Add Layout Manager
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
cp.add(but1);
show();
}

public static void main(String[] args){


SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
Add call to event handler
import javax.swing.*; import java.awt.*;
class SimpleGUI extends JFrame{
SimpleGUI(){
setSize(400,400); //set frames size in pixels
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton but1 = new JButton(“Click me”);
Container cp = getContentPane();//must do this
cp.setLayout(new FlowLayout(FlowLayout.CENTER);
but1.addActionListener(new MyActionListener());
cp.add(but1);
show();
}
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
System.out.println(“main thread coninues”);
}}
What are applets?
 Applet is a java program that runs in a web browser.

 The term applet derived from the word application to imply


applet is small applications.

36
…What Are Applets?

An applet is a special Java program that can be embedded in HTML


documents.

It is automatically executed by (applet-enabled) web browsers.

In Java, non-applet programs are called applications.

37
… applet program
1. Sub class Applet class.

2. Not define main method.

3. Design to be embedded with in an “html” page.

4. The code of the applet is downloaded when the user view the html page
contains applet.

5. The user must have JVM on its machine.

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 is an embeddable Panel, which is a simple Container window.

• An applet’s class must be public.

• An applet typically overrides the inherited init, start, stop, and paint methods.

• When a Web browser downloads an applet, it typically


• Invokes the init method to enable once-only initialization (e.g., setting colors,
fonts, and the like)
• Invokes the start method. If the applet is multithreaded, other threads can be
constructed and started in this method.
Syntax:
public class AppletClassName extends Applet
{
//

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.

You might also like