Container: Useful Methods of Component Class
Container: Useful Methods of Component Class
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.
Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame, Dialog and
Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void setLayout(LayoutManager m) defines the layout manager for the component.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}
Why AWT is platform dependent? Java AWT calls native platform (Operating systems)
subroutine for creating components such as textbox, checkbox, button etc. For example an
AWT GUI having a button would have a different look and feel across platforms like
windows, Mac OS & Unix, this is because these platforms have different look and feel for
their native buttons and AWT directly calls their native subroutine that creates the button. In
simple, an application build on AWT would look like a windows application when it runs on
Windows, but the same application would look like a Mac application when runs on Mac
OS.
AWT is rarely used now days because of its platform dependent and heavy-weight nature.
AWT components are considered heavy weight because they are being generated by
underlying operating system (OS). For example if you are instantiating a text box in AWT
that means you are actually asking OS to create a text box for you.
Swing is a preferred API for window based applications because of its platform
independent and light-weight nature. Swing is built upon AWT API however it provides a
look and feel unrelated to the underlying platform. It has more powerful and flexible
components than AWT. In addition to familiar components such as buttons, check boxes
and labels, Swing provides several advanced components such as tabbed panel, scroll
panes, trees, tables, and lists. We will discuss Swing in detail in a separate tutorial.
AWT hierarchy
Components and containers
All the elements like buttons, text fields, scrollbars etc are known as components. In AWT
we have classes for each component as shown in the above diagram. To have everything
placed on a screen to a particular position, we have to add them to a container. A container
is like a screen wherein we are placing components like buttons, text fields, checkbox etc.
In short a container contains and controls the layout of components. A container itself is a
component (shown in the above hierarchy diagram) thus we can add a container inside
container.
Types of containers:
As explained above, a container is a place wherein we add components like text field,
button, checkbox etc. There are four types of containers available in AWT: Window, Frame,
Dialog and Panel. As shown in the hierarchy diagram above, Frame and Dialog are
subclasses of Window class.
Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical
user interface components. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page
are the activities that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
Listener - It is also known as event handler.Listener is responsible for generating response
to an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received , the listener process the event
an then returns.
The benefit of this approach is that the user interface logic is completely separated
from the logic that generates the event. The user interface element is able to
delegate the processing of an event to the separate piece of code. In this model
,Listener needs to be registered with the source object so that the listener can
receive the event notification. This is an efficient way of handling the event because
the event notifications are sent only to those listener that want to receive them.
Callback Methods
These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represents an event method. In response to an event java jre will fire
callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the the source must
register itself to the listener.
AWT Color Class
Introduction
The Color class states colors in the default sRGB color space or colors in arbitrary
color spaces identified by a ColorSpace.
Class declaration
Following is the declaration for java.awt.Color class:
extends Object
Field
Following are the fields for java.awt.geom.Arc2D class:
Class constructors
S.N Constructor & Description
.
2
Color(float r, float g, float b)
4
Color(int rgb)
7
Color(int r, int g, int b, int a)
Class methods
S.N Method & Description
.
1 Color brighter()
2
PaintContext createContext(ColorModel cm,
Rectangle r, Rectangle2D r2d, AffineTransform
xform, RenderingHints hints)
3 Color darker()
6
int getAlpha()
7 int getBlue()
8
static Color getColor(String nm)
10
static Color getColor(String nm, int v)
12
float[] getColorComponents(float[] compArray)
Returns a float array containing only the color
components of the Color, in the ColorSpace of the Color.
13 ColorSpace getColorSpace()
14
float[] getComponents(ColorSpace cspace, float[]
compArray)
16
int getGreen()
18
int getRed()
19 int getRGB()
22
int getTransparency()
23 int hashCode()
24
static int HSBtoRGB(float hue, float saturation, float
brightness)
26
String toString()
java.lang.Object
Color Example
Create the following java program using any editor of your choice in say D:/ > AWT
> com > tutorialspoint > gui >
AWTGraphicsDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
prepareGUI();
awtGraphicsDemo.setVisible(true);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
@Override
Graphics2D g2 = (Graphics2D)g;
g2.setFont(plainFont);
g2.setColor(Color.red);
g2.setColor(Color.GRAY);
Compile the program using command prompt. Go to D:/ > AWT and type the
following command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using
following command.
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo
AWT Font Class
Introduction
The Font class states fonts, which are used to render text in a visible way.
Class declaration
Following is the declaration for java.awt.Font class:
extends Object
implements Serializable
Field
Following are the fields for java.awt.geom.Arc2D class:
Class constructors
S.N Constructor & Description
.
1 protected Font() ()
2
Font(Map<? extends
AttributedCharacterIterator.Attribute,?> attributes)
Class methods
S.N Method & Description
.
1
boolean canDisplay(char c)
3
int canDisplayUpTo(char[] text, int start, int limit)
5
int canDisplayUpTo(String str)
Returns a new Font using the specified font type and the
specified font file.
7
static Font createFont(int fontFormat, InputStream
fontStream)
9 GlyphVector createGlyphVector(FontRenderContext
frc, CharacterIterator ci)
10
GlyphVector createGlyphVector(FontRenderContext
frc, int[] glyphCodes)
11 GlyphVector createGlyphVector(FontRenderContext
frc, String str)
12
static Font decode(String str)
14
Font deriveFont(float size)
17
Font deriveFont(int style, float size)
19
boolean equals(Object obj)
21
Map<TextAttribute,?> getAttributes()
22 AttributedCharacterIterator.Attribute[]
getAvailableAttributes()
24 String getFamily()
25
String getFamily(Locale l)
27
static Font getFont(String nm)
29
String getFontName()
30 String getFontName(Locale l)
Returns the font face name of the Font, localized for the
specified locale.
31
float getItalicAngle()
34
LineMetrics getLineMetrics(String str,
FontRenderContext frc)
36
Rectangle2D
getMaxCharBounds(FontRenderContext frc)
37 int getMissingGlyphCode()
38
String getName()
40 java.awt.peer.FontPeer getPeer()
41
String getPSName()
42 int getSize()
43
float getSize2D()
45
Rectangle2D getStringBounds(CharacterIterator ci,
int beginIndex, int limit, FontRenderContext frc)
48 int getStyle()
49
AffineTransform getTransform()
50 int hashCode()
51
boolean hasLayoutAttributes()
52 boolean hasUniformLineMetrics()
53
boolean isBold()
54 boolean isItalic()
55
boolean isPlain()
57 GlyphVector layoutGlyphVector(FontRenderContext
frc, char[] text, int start, int limit, int flags)
58
String toString()
Methods inherited
This class inherits methods from the following classes:
java.lang.Object
Font Example
Create the following java program using any editor of your choice in say D:/ > AWT
> com > tutorialspoint > gui >
AWTGraphicsDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
awtGraphicsDemo.setVisible(true);
setSize(400,400);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
@Override
Graphics2D g2 = (Graphics2D)g;
g2.setFont(plainFont);
g2.setFont(italicFont);
g2.setFont(boldFont);
g2.setFont(boldItalicFont);
Compile the program using command prompt. Go to D:/ > AWT and type the
following command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using
following command.
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo
Java LayoutManagers
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu
must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm
dialog box and input dialog box. These dialog boxes are used to display information or get input from
the user. The JOptionPane class inherits JComponent class.
Constructor Description
Methods Description
static void showMessageDialog(Component parentComponent, It is used to create a message dialog with given
Object message, String title, int messageType) messageType.
static int showConfirmDialog(Component parentComponent, It is used to create a dialog with the options Ye
Object message) Cancel; with the title, Select an Option.
void setInputValue(Object newValue) It is used to set the input value that was select
the user.