You are on page 1of 48

Graphics and

Frames in Java
• Java AWT (Abstract Window Toolkit) is an API
to develop GUI or window-based applications in
java.
• Java AWT components are platform-
dependent i.e. components are displayed
according to the view of operating system.
• AWT is heavyweight i.e. its components are
using the resources of OS.
• AWT is huge! It consists of 12 packages of 370
classes
• The java.awt package provides classes for AWT
api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
10/13/2019 2
AWT Hierarchy

10/13/2019 3
The java.awt package contains the core AWT graphics
classes
•GUI Component classes, such as Button, TextField,
and Label.
•GUI Container classes, such as Frame and Panel.
•Layout managers, such
as FlowLayout, BorderLayout and GridLayout.
•Custom graphics classes, such
as Graphics, Color and Font.

13-10-2019 4
Container
• Container Class is a subclass of Component. It has
additional methods that allow other Component objects
nested within it.
• Other Container objects can be stored inside of a
Container (since they are themselves instances of
Component). This makes for multivalued containment
system.
• A container is responsible for laying out any components
that it contains.

13-10-2019 5
Difference Between Container
and Component
• Container and Component are standard classes in Java.
• The main difference between them is that a Container is a
subclass of Component which can contain
other components and containers.
• Frame, Panel and Applet are subclasses of Container.
A Container helps to create groupings of objects on the
screen.
• Component: Components are elementary GUI entities, such
as Button, Label, and TextField.
• Container: Containers, such as Frame and Panel, are used
to hold components in a specific layout (such as FlowLayout
or GridLayout). A container can also hold sub-containers.

13-10-2019 6
Panel
• Panel is a concrete subclass of container.
• Other components can be added to a Panel object by its
add method (inherited from Container).
• Panel: A Panel is a rectangular area used to group
related GUI components in a certain layout but it doesn't
have title bar, menu bar
• Once these Components have been added, you can
position abd resize them manually using setLocation,
setSize(), setPreferredSize(), setBounds methods
defined by Component.

13-10-2019 7
Window
• Window class creates a top-level window.
• The top-level window is no contained
within any other object; it sits directly on
the desktop.
• Window: It is also container but no border
and menu bar
• We won’t create Window objects directly.
• Instead, subclass of window called Frame
can be used.
13-10-2019 8
Frame
• A Frame is the top-level container of an AWT program.
• Frame encapsulates what is commonly thought of as a
window.
• It is subclass of Window.
• A Frame has a title bar (containing an icon, a title, and
the minimize/maximize/close buttons), an optional menu
bar and the content display area.

13-10-2019 9
• A Frame provides the "main window" for your GUI
application. It has a title bar (containing an icon, a title,
the minimize, maximize/restore-down and close buttons),
an optional menu bar, and the content display area.
• To write a GUI program, we typically start with a
subclass extending from java.awt.Frame to inherit the
main window as follows:

13-10-2019 10
13-10-2019 11
Dialog and Applet
• An AWT Dialog is a "pop-up window" used for interacting
with the users. A Dialog has a title-bar (containing an
icon, a title and a close button) and a content display
area, as illustrated.
• An AWT Applet (in package java.applet) is the top-level
container for an applet, which is a Java program running
inside a browser.

13-10-2019 12
Important Points
• In a GUI program, a component must be kept in a
container. You need to identify a container to hold the
components. Every container has a method called
add(Component c).

13-10-2019 13
Setting Window’s Size
• setSize(): method is used to set the
dimension of the windows.
– void setSize(int newwidth, int newheight )
– void setSize(Dimension newSize)
• getSize() method is used to obtain the
current size of window.
– Dimension getSize()

13-10-2019 14
Hiding and Showing Window
• After a frame window has been created, it
will not be visible until you call setVisible().
– Void setVisible(boolen visibleFlag)

13-10-2019 15
Setting a Window’s Title
• We can change the title in a frame window
using setTitle().
– void setTitle(String newTitle)

13-10-2019 16
Closing a Frame Window
• Your program must remove that window
from screen when it is closed.
• If it is not top-level window of your
application, this is done by calling
setVisible(false).
• For main application window, terminate
the program by calling System.exit().

13-10-2019 17
Paint() Method
• Output to a window typically occurs when
paint method is called by the run-time
system.
• This method is defined by Component and
overridden by Container and Window
and thus it is available to instances of
Frame.

13-10-2019 18
• Paint() method is called each time an AWT-based
application’s output must be redrawn.
• Ex- program’s window may be overwritten by another
window and then uncovered.
• Thus , whenever the window must redraw its output,
paint() is called.
• This implies that your program must have some way to
retrain its output so that it can be redisplayed each time
paint() executes.
– void paint(Graphics context)
• The paint() method has one parameter of type Graphics.
This parameter will contain the graphics context, which
describes the graphics environment in which program is
running.

13-10-2019 19
Displaying String
• To output a string to a Frame, use
drawString(), which is a member of
graphics class.
– void drawstring(String message, int x, int y)

13-10-2019 20
Setting Foreground and Background
Colours
• We can set the foreground and background colors used
by a Frame.
• To set background: setBackground(Color newColor);
• to set foreground: setForeground(Color newColor);
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray

13-10-2019 21
• We can obtain the current settings for the
background and foreground colors by
calling getBackground() and
getForeground().
– Colors getBackground()
– Colors getForeground()

13-10-2019 22
Creating Framed-Based
Application
• Create the subclass of Frame and override
paint() to supply your output to the
window.
• In all cases, we have to implement the
windowClosing() method of the
WindowListner interface.
• To simply remove a secondary frame from
the screen, you can call setVisible(false)
when the window is closed.
13-10-2019 23
Graphics
• AWT includes number of methods that supports
graphics.
• This can be main windows of an application or a child
window.
• Graphics Context encapsulated by the Graphics class.
– It is passed to a method such as paint() or update() as
an argument
– It is returned by the getGraphics() method of
Component

13-10-2019 24
• Graphics class defines number of methods
that draw various types of object such as:
– Lines
– Rectangles
– Arcs
• Object can be drawn edge only or filled

13-10-2019 25
Drawing Different Shapes
• void drawLine(int startX, int startY, int endX, int endY)
• void drawRect(int left, int top, int width, int height)
• void fillRect (int left, int top, int width, int height)
• void drawRoundRect(int left, int top, int width, int height,
int xDiam, int yDiam)
• void fillRoundRect(int left, int top, int width, int height, int
xDiam, int yDiam)

13-10-2019 26
• Ellipse and Circle:
– drawOval(int left, int top, int width, int height)
– fillOval(int left, int top, int width, int height)
• Drawing Arcs
– The arc is bounded by the rectangle whose upper-left
corner is specified by left, top and whose width and
height are specified by sweep angle.
– drawArc (int left, int top, int width, int height, int
startAngle, int sweepAngle)
– fillArc(int left, int top, int width, int height, int
startAngle, int sweepAngle)

13-10-2019 27
Drawing Polygon
• void drawPolygoan(int x, int y, int numPoints)
• void fillPolygoan(int x, int y, int numPoints)

13-10-2019 28
Sizing Graphics
• First obtain the current dimensions of the frame by calling
geSize().
• It returns the dimensions as integer values stored in the width
and height fields of the frame including title bar and border.
• To obtain the dimensions of the paintable area, we will need
to reduce the size obtained from getSize() by the dimensions
of the border and title bar.

13-10-2019 29
Insets
• The values that describes the size of the border/title region
are called insets.
• The insets values are obtained by calling getInsets().
• It returns an Insets object that encapsulates the insets
dimensions as four int values called left, right, top and bottom.
• The co-ordinates of the top-left corner of the paintable area is
left, top.
• The co-ordinate of the bottom-right corner is width-right,
height-bottom.

13-10-2019 30
Working with Colors
• Own Colors
– Color(int red, int green, int blue)
– Color(int rgb)
– Color(float red, float green, float blue)

13-10-2019 31
Using Hue, Saturation &
Brightness
• HSB alternative to the RGB
• Range is 0.0-1.0
• Static int HSBtoRGB(float hue, float Saturation, float
Brightness)
• Static float [] RGBtoHSB)(int red, int green, int blues, float
values[])

13-10-2019 32
Working with Fonts
• The AWT supports multiple type fonts.
• Fonts have a family name, a logical font name, and a
face name. The family name is the general name of the
font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name
specifies a specific font, such as Courier Italic.

13-10-2019 33
13-10-2019 34
Determining the Available Fonts
• To obtain the information of fonts that are
available on your machine, we can use the
getAvailableFontFamilyNames() method
defined by GraphicsEnvironment class
– String [] getAvailableFontFamilyNames()
• This method returns an array of strings that
contains the names of the available font families.

13-10-2019 35
• The getAllFonts() method is defined by the
GraphicsEnvironment class.
– Font [] getAllFonts()
– This method returns array Font objects for all of the
available fonts.
• All these methods are members of
GraphicsEnvironment, we need a
GraphicsEnvironment reference (Object) to call these
methods.

13-10-2019 36
import java.awt.event.*; public void piant(Graphics g) {
import java.awt.*; g.setColor(Color.CYAN);
g.drawString(msg, 100, 600);
public class ShowFonts extends Frame { }
String msg = "First Five Fonts: ";
GraphicsEnvironment ge; public static void main(String[] args) {
public ShowFonts() { ShowFonts sf = new ShowFonts();
addWindowListener(new WindowAdapter() { sf.setSize(370,100);
public void windowClosing(WindowEvent we) { sf.setTitle("Font List");
System.exit(0); sf.setVisible(true);
}
}); }
//Get the Graphics environment
ge = }
GraphicsEnvironment.getLocalGraphicsEnvironm
ent();

//obtain a list of the fonts


String
fontList[]=ge.getAvailableFontFamilyNames();

//create a string of the first 10 fonts


for(int i=0;i< fontList.length;i++)
msg=msg+fontList[i]+ " ";
System.out.println(msg);
}

13-10-2019 37
Setting the Paint Mode
• XOR or Exclusive Or returns true only if both its operands have
different values. The XOR shows the uncommon part. We are
providing you an example which shows the XOR mode.
• The paint mode determines how objects are drawn in a window. By
default, new output to a window overwrites any preexisting contents.
However, it is possible to have new objects XORed onto the window
by using setXORMode( ), as follows:
– void setXORMode(Color xorColor)
• Here, xorColor specifies the color that will be XORed to the window
when an object is drawn. The advantage of XOR mode is that the
new object is always guaranteed to be visible no matter what color
the object is drawn over.

13-10-2019 38
AWT Component Classes
• AWT provides many ready-made and reusable GUI
components in package java.awt. The frequently-used
are: Button, TextField, Label, Checkbox,
CheckboxGroup (radio buttons), List, and Choice

13-10-2019 39
• A java.awt.Label provides a descriptive text string. Take
note that System.out.println() prints to the system
console, NOT to the graphics screen. You could use a
Label to label another component (such as text field) to
provide a text description.
• public Label(String strLabel, int alignment); // Construct a Label with the given text
String, of the text alignment
• public Label(String strLabel); // Construct a Label with the given text String
• public Label(); // Construct an initially empty Label

13-10-2019 40
• The Label class has three constructors:
• The first constructor constructs a Label object with the given
text string in the given alignment. Note that three static
constants Label.LEFT, Label.RIGHT, and Label.CENTER are
defined in the class for you to specify the alignment (rather
than asking you to memorize arbitrary integer values).
• The second constructor constructs a Label object with the
given text string in default of left-aligned.
• The third constructor constructs a Label object with an initially
empty string. You could set the label text via the setText()
method later.

13-10-2019 41
Constructing a Component and Adding the Component
into a Container

• Declare the component with an identifier (name);


• Construct the component by invoking an appropriate
constructor via the new operator;
• Identify the container (such as Frame or Panel) designed
to hold this component. The container can then add this
component onto itself via aContainer.add(aComponent)
method. Every container has a add(Component) method.
Take note that it is the container that actively and
explicitly adds a component onto itself, NOT the other
way.

13-10-2019 42
13-10-2019 43
AWT GUI Component: java.awt.Button

• A java.awt.Button is a GUI component that triggers a


certain programmed action upon clicking.

public Button(String btnLabel); // Construct a Button


with the given label
public Button(); // Construct a Button with empty label

13-10-2019 44
public String getLabel(); // Get the label of this Button instance
public void setLabel(String btnLabel); // Set the label of this Button instance
public void setEnable(boolean enable); // Enable or disable this Button. Disabled Button
cannot be clicked.

13-10-2019 45
AWT GUI Component: java.awt.TextField

• A java.awt.TextField is single-line text box for users to enter


texts. (There is a multiple-line text box called TextArea.)
Hitting the "ENTER" key on a TextField object fires an
ActionEvent.
public TextField(String initialText, int columns);
// Construct a TextField instance with the given initial text string with
the number of columns.
public TextField(String initialText);
// Construct a TextField instance with the given initial text string.
public TextField(int columns);
// Construct a TextField instance with the number of columns.

13-10-2019 46
public String getText();
// Get the current text on this TextField instance
public void setText(String strText);
// Set the display text on this TextField instance
public void setEditable(boolean editable);
// Set this TextField to editable (read/write) or non-editable (read-only)

13-10-2019 47
13-10-2019 48

You might also like