0% found this document useful (0 votes)
84 views

Container: Useful Methods of Component Class

Java AWT is an API for creating GUI applications in Java. It is platform-dependent as AWT components are rendered differently on different operating systems. The java.awt package provides classes for common GUI components like buttons, labels, text fields etc. Containers like Frame, Dialog and Panel are used to hold other components. Frame is the most commonly used container as it displays a window with a title bar and can contain menus. The AWT example code shows how to create a simple GUI application using a Frame container by both extending the Frame class and creating a Frame object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

Container: Useful Methods of Component Class

Java AWT is an API for creating GUI applications in Java. It is platform-dependent as AWT components are rendered differently on different operating systems. The java.awt package provides classes for common GUI components like buttons, labels, text fields etc. Containers like Frame, Dialog and Panel are used to hold other components. Frame is the most commonly used container as it displays a window with a title bar and can contain menus. The AWT example code shows how to create a simple GUI application using a Frame container by both extending the Frame class and creating a Frame object.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

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.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,


RadioButton, CheckBox, Choice, List etc.

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.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.


public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component,


by default false.

Java AWT Example


To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing Button
component on the Frame.

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

AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating


Graphical User Interface (GUI) for java programs.

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.

Window: An instance of the Window class has no border and no title


Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist
without an associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for
holding components. An instance of the Panel class provides a container to which to add
components.
Frame: A frame has title, border and menu bars. It can contain several components like
buttons, text fields, scrollbars etc. This is most widely used container while developing an
application in AWT.

Java AWT Example


We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.

AWT Example 1: creating Frame by extending Frame


class
import java.awt.*;
/* We have extended the Frame class here,
 * thus our class "SimpleExample" would behave
 * like a Frame
 */
public class SimpleExample extends Frame{
    SimpleExample(){  
        Button b=new Button("Button!!");
        
        // setting button position on screen
        b.setBounds(50,50,50,50);  
        
        //adding button into frame
        add(b);
        
        //Setting Frame width and height
        setSize(500,300);
        
        //Setting the title of Frame
        setTitle("This is my First AWT example");
        
        //Setting the layout for the Frame
        setLayout(new FlowLayout());
        
        /* By default frame is not visible so
         * we are setting the visibility to true
         * to make it visible.
         */
        setVisible(true);  
    }  
    public static void main(String args[]){  
         // Creating the instance of Frame
         SimpleExample fr=new SimpleExample();  
    }
}
Output:
AWT Example 2: creating Frame by creating instance of
Frame class
import java.awt.*;
public class Example2 {
Example2()
   {
      //Creating Frame    
      Frame fr=new Frame();       
      
      //Creating a label
      Label lb = new Label("UserId: ");
      
      //adding label to the frame
      fr.add(lb);           
      
      //Creating Text Field
      TextField t = new TextField();
      
      //adding text field to the frame
      fr.add(t);
      
      //setting frame size
      fr.setSize(500, 300);  
      
      //Setting the layout for the Frame
      fr.setLayout(new FlowLayout());
            
      fr.setVisible(true);                
   }
   public static void main(String args[])
   {
       Example2 ex = new Example2();
   }
}
Output:
What is an Event?

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.

What is Event Handling?


Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event
Model to handle the events. This model defines the standard mechanism to generate
and handle the events.Let's have a brief introduction to this model.

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.

Steps involved in event handling


 The User clicks the button and the event is generated.
 Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener interfaces.These
Listener interfaces forecast some public abstract callback methods which must be
implemented by the listener class.
 If you do not implement the any if the predefined interfaces then your class can not act as
a listener class for a source object.

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:

public class Color

extends Object

implements Paint, Serializable

Field
Following are the fields for java.awt.geom.Arc2D class:

 static Color black -- The color black.


 static Color BLACK -- The color black.
 static Color blue -- The color blue.
 static Color BLUE -- The color blue.
 static Color cyan -- The color cyan.
 static Color CYAN -- The color cyan.
 static Color DARK_GRAY -- The color dark gray.
 static Color darkGray -- The color dark gray.
 static Color gray -- The color gray.
 static Color GRAY -- The color gray.
 static Color green -- The color green.
 static Color GREEN -- The color green.
 static Color LIGHT_GRAY -- The color light gray.
 static Color lightGray -- The color light gray.
 static Color magenta -- The color magenta.
 static Color MAGENTA -- The color magenta.
 static Color orange -- The color orange.
 static Color ORANGE -- The color orange.
 static Color pink -- The color pink.
 static Color PINK -- The color pink.
 static Color red -- The color red.
 static Color RED -- The color red.
 static Color white -- The color white.
 static Color WHITE -- The color white.
 static Color yellow -- The color yellow.
 static Color YELLOW -- The color yellow.

Class constructors
S.N Constructor & Description
.

1 Color(ColorSpace cspace, float[] components, float


alpha)

Creates a color in the specified ColorSpace with the color


components specified in the float array and the specified
alpha.

2
Color(float r, float g, float b)

Creates an opaque sRGB color with the specified red,


green, and blue values in the range (0.0 - 1.0).

3 Color(float r, float g, float b, float a)

Creates an sRGB color with the specified red, green, blue,


and alpha values in the range (0.0 - 1.0).

4
Color(int rgb)

Creates an opaque sRGB color with the specified


combined RGB value consisting of the red component in
bits 16-23, the green component in bits 8-15, and the
blue component in bits 0-7.
5
Color(int rgba, boolean hasalpha)

Creates an sRGB color with the specified combined RGBA


value consisting of the alpha component in bits 24-31, the
red component in bits 16-23, the green component in bits
8-15, and the blue component in bits 0-7.

6 Color(int r, int g, int b)

Creates an opaque sRGB color with the specified red,


green, and blue values in the range (0 - 255).

7
Color(int r, int g, int b, int a)

Creates an sRGB color with the specified red, green, blue,


and alpha values in the range (0 - 255).

Class methods
S.N Method & Description
.

1 Color brighter()

Creates a new Color that is a brighter version of this


Color.

2
PaintContext createContext(ColorModel cm,
Rectangle r, Rectangle2D r2d, AffineTransform
xform, RenderingHints hints)

Creates and returns a PaintContext used to generate a


solid color pattern.

3 Color darker()

Creates a new Color that is a darker version of this Color.


4
static Color decode(String nm)

Converts a String to an integer and returns the specified


opaque Color.

5 boolean equals(Object obj)

Determines whether another object is equal to this Color.

6
int getAlpha()

Returns the alpha component in the range 0-255.

7 int getBlue()

Returns the blue component in the range 0-255 in the


default sRGB space.

8
static Color getColor(String nm)

Finds a color in the system properties.

9 static Color getColor(String nm, Color v)

Finds a color in the system properties.

10
static Color getColor(String nm, int v)

Finds a color in the system properties.

11 float[] getColorComponents(ColorSpace cspace,


float[] compArray)

Returns a float array containing only the color


components of the Color in the ColorSpace specified by
the cspace parameter.

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

Returns the ColorSpace of this Color.

14
float[] getComponents(ColorSpace cspace, float[]
compArray)

Returns a float array containing the color and alpha


components of the Color, in the ColorSpace specified by
the cspace parameter.

15 float[] getComponents(float[] compArray)

Returns a float array containing the color and alpha


components of the Color, in the ColorSpace of the Color.

16
int getGreen()

Returns the green component in the range 0-255 in the


default sRGB space.

17 static Color getHSBColor(float h, float s, float b)

Creates a Color object based on the specified values for


the HSB color model.

18
int getRed()

Returns the red component in the range 0-255 in the


default sRGB space.

19 int getRGB()

Returns the RGB value representing the color in the


default sRGB ColorModel.
20
float[] getRGBColorComponents(float[] compArray)

Returns a float array containing only the color


components of the Color, in the default sRGB color space.

21 float[] getRGBComponents(float[] compArray)

Returns a float array containing the color and alpha


components of the Color, as represented in the default
sRGB color space.

22
int getTransparency()

Returns the transparency mode for this Color.

23 int hashCode()

Computes the hash code for this Color.

24
static int HSBtoRGB(float hue, float saturation, float
brightness)

Converts the components of a color, as specified by the


HSB model, to an equivalent set of values for the default
RGB model.

25 static float[] RGBtoHSB(int r, int g, int b, float[]


hsbvals)

Converts the components of a color, as specified by the


default RGB model, to an equivalent set of values for hue,
saturation, and brightness that are the three components
of the HSB model.

26
String toString()

Returns a string representation of this Color.


Methods inherited
This class inherits methods from the following classes:

 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 class AWTGraphicsDemo extends Frame {

public AWTGraphicsDemo(){

super("Java AWT Examples");

prepareGUI();

public static void main(String[] args){

AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();

awtGraphicsDemo.setVisible(true);

private void prepareGUI(){


setSize(400,400);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

@Override

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D)g;

Font plainFont = new Font("Serif", Font.PLAIN, 24);

g2.setFont(plainFont);

g2.setColor(Color.red);

g2.drawString("Welcome to TutorialsPoint", 50, 70);

g2.setColor(Color.GRAY);

g2.drawString("Welcome to TutorialsPoint", 50, 120);

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:

public class Font

extends Object

implements Serializable

Field
Following are the fields for java.awt.geom.Arc2D class:

 static int BOLD -- The bold style constant.


 static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese,
Japanese, and Korean when laying out text.
 static String DIALOG --A String constant for the canonical family name of the logical font
"Dialog".
 static String DIALOG_INPUT --A String constant for the canonical family name of the
logical font "DialogInput".
 static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts
when laying out text.
 static int ITALIC -- The italicized style constant.
 static int LAYOUT_LEFT_TO_RIGHT -- A flag to layoutGlyphVector indicating that text is
left-to-right as determined by Bidi analysis.
 static int LAYOUT_NO_LIMIT_CONTEXT -- A flag to layoutGlyphVector indicating that
text in the char array after the indicated limit should not be examined.
 static int LAYOUT_NO_START_CONTEXT -- A flag to layoutGlyphVector indicating that
text in the char array before the indicated start should not be examined.
 static int LAYOUT_RIGHT_TO_LEFT -- A flag to layoutGlyphVector indicating that text is
right-to-left as determined by Bidi analysis.
 static String MONOSPACED -- A String constant for the canonical family name of the
logical font "Monospaced".
 protected String name -- The logical name of this Font, as passed to the constructor.
 static int PLAIN --The plain style constant.
 protected float pointSize -- The point size of this Font in float.
 static int ROMAN_BASELINE --The baseline used in most Roman scripts when laying out
text.
 static String SANS_SERIF -- A String constant for the canonical family name of the
logical font "SansSerif".
 static String SERIF -- A String constant for the canonical family name of the logical font
"Serif".
 protected int size --The point size of this Font, rounded to integer.
 protected int style -- The style of this Font, as passed to the constructor.
 static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE.
 static int TYPE1_FONT -- Identify a font resource of type TYPE1.

Class constructors
S.N Constructor & Description
.

1 protected Font() ()

Creates a new Font from the specified font.

2
Font(Map<? extends
AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font from the specified font.

3 Font(String name, int style, int size)

Creates a new Font from the specified font.

Class methods
S.N Method & Description
.

1
boolean canDisplay(char c)

Checks if this Font has a glyph for the specified character.

2 boolean canDisplay(int codePoint)

Checks if this Font has a glyph for the specified character.

3
int canDisplayUpTo(char[] text, int start, int limit)

Indicates whether or not this Font can display the


characters in the specified text starting at start and
ending at limit.

4 int canDisplayUpTo(CharacterIterator iter, int start,


int limit)

Indicates whether or not this Font can display the text


specified by the iter starting at start and ending at limit.

5
int canDisplayUpTo(String str)

Indicates whether or not this Font can display a specified


String.

6 static Font createFont(int fontFormat, File fontFile)

Returns a new Font using the specified font type and the
specified font file.

7
static Font createFont(int fontFormat, InputStream
fontStream)

Returns a new Font using the specified font type and


input data.
8
GlyphVector createGlyphVector(FontRenderContext
frc, char[] chars)

Creates a GlyphVector by mapping characters to glyphs


one-to-one based on the Unicode cmap in this Font.

9 GlyphVector createGlyphVector(FontRenderContext
frc, CharacterIterator ci)

Creates a GlyphVector by mapping the specified


characters to glyphs one-to-one based on the Unicode
cmap in this Font.

10
GlyphVector createGlyphVector(FontRenderContext
frc, int[] glyphCodes)

Creates a GlyphVector by mapping characters to glyphs


one-to-one based on the Unicode cmap in this Font.

11 GlyphVector createGlyphVector(FontRenderContext
frc, String str)

Creates a GlyphVector by mapping characters to glyphs


one-to-one based on the Unicode cmap in this Font.

12
static Font decode(String str)

Returns the Font that the str argument describes.

13 Font deriveFont(AffineTransform trans)

Creates a new Font object by replicating the current Font


object and applying a new transform to it.

14
Font deriveFont(float size)

Creates a new Font object by replicating the current Font


object and applying a new size to it.
15
Font deriveFont(int style)

Creates a new Font object by replicating the current Font


object and applying a new style to it.

16 Font deriveFont(int style, AffineTransform trans)

Creates a new Font object by replicating this Font object


and applying a new style and transform.

17
Font deriveFont(int style, float size)

Creates a new Font object by replicating this Font object


and applying a new style and size.

18 Font deriveFont(Map<? extends


AttributedCharacterIterator.Attribute,?> attributes)

Creates a new Font object by replicating the current Font


object and applying a new set of font attributes to it.

19
boolean equals(Object obj)

Compares this Font object to the specified Object.

20 protected void finalize()

Disposes the native Font object.

21
Map<TextAttribute,?> getAttributes()

Returns a map of font attributes available in this Font.

22 AttributedCharacterIterator.Attribute[]
getAvailableAttributes()

Returns the keys of all the attributes supported by this


Font.
23
byte getBaselineFor(char c)

Returns the baseline appropriate for displaying this


character.

24 String getFamily()

Returns the family name of this Font.

25
String getFamily(Locale l)

Returns the family name of this Font, localized for the


specified locale.

26 static Font getFont(Map<? extends


AttributedCharacterIterator.Attribute,?> attributes)

Returns a Font appropriate to the attributes.

27
static Font getFont(String nm)

Returns a Font object fom the system properties list.

28 static Font getFont(String nm, Font font)

Gets the specified Font from the system properties list.

29
String getFontName()

Returns the font face name of this Font.

30 String getFontName(Locale l)

Returns the font face name of the Font, localized for the
specified locale.

31
float getItalicAngle()

Returns the italic angle of this Font.


32
LineMetrics getLineMetrics(char[] chars, int
beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified


arguments.

33 LineMetrics getLineMetrics(CharacterIterator ci, int


beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified


arguments.

34
LineMetrics getLineMetrics(String str,
FontRenderContext frc)

Returns a LineMetrics object created with the specified


String and FontRenderContext.

35 LineMetrics getLineMetrics(String str, int


beginIndex, int limit, FontRenderContext frc)

Returns a LineMetrics object created with the specified


arguments.

36
Rectangle2D
getMaxCharBounds(FontRenderContext frc)

Returns the bounds for the character with the maximum


bounds as defined in the specified FontRenderContext.

37 int getMissingGlyphCode()

Returns the glyphCode which is used when this Font does


not have a glyph for a specified unicode code point.

38
String getName()

Returns the logical name of this Font.


39
int getNumGlyphs()

Returns the number of glyphs in this Font.

40 java.awt.peer.FontPeer getPeer()

Deprecated. Font rendering is now platform independent.

41
String getPSName()

Returns the postscript name of this Font.

42 int getSize()

Returns the point size of this Font, rounded to an integer.

43
float getSize2D()

Returns the point size of this Font in float value.

44 Rectangle2D getStringBounds(char[] chars, int


beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified array of


characters in the specified FontRenderContext.

45
Rectangle2D getStringBounds(CharacterIterator ci,
int beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the characters indexed in


the specified CharacterIterator in the specified
FontRenderContext.

46 Rectangle2D getStringBounds(String str,


FontRenderContext frc)

Returns the logical bounds of the specified String in the


specified FontRenderContext.
47
Rectangle2D getStringBounds(String str, int
beginIndex, int limit, FontRenderContext frc)

Returns the logical bounds of the specified String in the


specified FontRenderContext.

48 int getStyle()

Returns the style of this Font.

49
AffineTransform getTransform()

Returns a copy of the transform associated with this Font.

50 int hashCode()

Returns a hashcode for this Font.

51
boolean hasLayoutAttributes()

Return true if this Font contains attributes that require


extra layout processing.

52 boolean hasUniformLineMetrics()

Checks whether or not this Font has uniform line metrics.

53
boolean isBold()

Indicates whether or not this Font object's style is BOLD.

54 boolean isItalic()

Indicates whether or not this Font object's style is ITALIC.

55
boolean isPlain()

Indicates whether or not this Font object's style is PLAIN.


56
boolean isTransformed()

Indicates whether or not this Font object has a transform


that affects its size in addition to the Size attribute.

57 GlyphVector layoutGlyphVector(FontRenderContext
frc, char[] text, int start, int limit, int flags)

Returns a new GlyphVector object, performing full layout


of the text if possible.

58
String toString()

Converts this Font object to a String representation.

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 class AWTGraphicsDemo extends Frame {

public AWTGraphicsDemo(){
super("Java AWT Examples");

prepareGUI();

public static void main(String[] args){

AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();

awtGraphicsDemo.setVisible(true);

private void prepareGUI(){

setSize(400,400);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

@Override

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D)g;

Font plainFont = new Font("Serif", Font.PLAIN, 24);

g2.setFont(plainFont);

g2.drawString("Welcome to TutorialsPoint", 50, 70);

Font italicFont = new Font("Serif", Font.ITALIC, 24);

g2.setFont(italicFont);

g2.drawString("Welcome to TutorialsPoint", 50, 120);


Font boldFont = new Font("Serif", Font.BOLD, 24);

g2.setFont(boldFont);

g2.drawString("Welcome to TutorialsPoint", 50, 170);

Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);

g2.setFont(boldItalicFont);

g2.drawString("Welcome to TutorialsPoint", 50, 220);

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

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an


interface that is implemented by all the classes of layout managers. There are following classes that
represents the layout managers:

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:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

Java AWT MenuItem and Menu

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.

AWT MenuItem class declaration


1. public class MenuItem extends MenuComponent implements Accessible  

AWT Menu class declaration


1. public class Menu extends MenuItem implements MenuContainer, Accessible  

Java AWT MenuItem and Menu Example


1. import java.awt.*;  
2. class MenuExample  
3. {  
4.      MenuExample(){  
5.          Frame f= new Frame("Menu and MenuItem Example");  
6.          MenuBar mb=new MenuBar();  
7.          Menu menu=new Menu("Menu");  
8.          Menu submenu=new Menu("Sub Menu");  
9.          MenuItem i1=new MenuItem("Item 1");  
10.          MenuItem i2=new MenuItem("Item 2");  
11.          MenuItem i3=new MenuItem("Item 3");  
12.          MenuItem i4=new MenuItem("Item 4");  
13.          MenuItem i5=new MenuItem("Item 5");  
14.          menu.add(i1);  
15.          menu.add(i2);  
16.          menu.add(i3);  
17.          submenu.add(i4);  
18.          submenu.add(i5);  
19.          menu.add(submenu);  
20.          mb.add(menu);  
21.          f.setMenuBar(mb);  
22.          f.setSize(400,400);  
23.          f.setLayout(null);  
24.          f.setVisible(true);  
25. }  
26. public static void main(String args[])  
27. {  
28. new MenuExample();  
29. }  
30. }  

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.

JOptionPane class declaration


1. public class JOptionPane extends JComponent implements Accessible  
Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a message.

JOptionPane(Object message, int It is used to create an instance of JOptionPane to display a message


messageType message type and default options.

Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new parentless


the specified title.

static void showMessageDialog(Component parentComponent, It is used to create an information-message dia


Object message) "Message".

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.

static String showInputDialog(Component parentComponent, It is used to show a question-message dialog re


Object message) from the user parented to parentComponen

void setInputValue(Object newValue) It is used to set the input value that was select
the user.

Java JOptionPane Example: showMessageDialog()


1. import javax.swing.*;  
2. public class OptionPaneExample {  
3. JFrame f;  
4. OptionPaneExample(){  
5.     f=new JFrame();  
6.     JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");  
7. }  
8. public static void main(String[] args) {  
9.     new OptionPaneExample();  
10. }  
11. }  

You might also like