Você está na página 1de 16

AWT Components

- The basic idea behind the AWT is that a java window is a set of nested
components starting from the outermost window all the way down to the
smallest User Interface component.

- The AWT classes are contained in the java.awt package. It is one of the
java’s largest packages.

- The AWT provides the basic GUI components that are used in java applets
and applications. The AWT provides a machine-independent interface for
applications.

- The AWT classes provides the following:

a) A fell set of UI widgets and other components, including windows,


menus, buttons, checkboxes etc.
b) Support for UI containers, which can contain other embedded
containers and widgets.
c) Provision of Layout Managers whose duty is to handle the laying out
of components on Containers.
d) An event system for managing system and user events between and
among parts of the AWT

- Java Components are implemented by the many subclasses of the


java.awt.Component and java.awt.MenuComponent superclass. There are
19 non-superclasses in general. The general way to categories them is to
divide them into the following categories:

a) Visual Components
b) Container Components
c) Menu Components

The fundamental visual controls in java are:

1. Label – A simple label

2. Button – A simple push button

3. Canvas – A base class for creating your own controls.

4. Checkbox – A combination of check box and radio (option) button

5. Choice – A drop down list control

6. FileDialog – Which represents a File Open or Save Dialog


7. List – A list box

8. Scroll bar – Horizontal and Vertical Scroll bar

9. Scroll Pane – A scrollable pane where areas of larger components can


be shows

10. Text Field – A single line text entry field

11. Text Area – A multiple line text entry field

The most common methods in the Object and Component classes are:

1. setBounds Changes control shape and location


2. setSize Changes control size
3. setEnabled Sets control to active or inactive
4. setBackground Sets background color
5. getBackground Gets background color
6. isEnabled Returns boolean indicating whether currently
enables
7. isVisible Returns boolean indicating whether control is
visible
8. getLocation Returns the x and y location
9. setLocation Moves the control to a new location
1 requestFocus Asks system to give focus to control
0.
11 getBackground Sets Background Color
.
1 getForeground Sets Foreground Color
2.
1 setFont Sets font to font , style and size
3.
1 getSize Returns the current size of control
4.

Containers

- The containers contain individual components inside them.

- The two important things done with the container is establishing the
container’s layout manager and adding components to the container.
Container is the abstract subclass of component, which allows other
components to be nested inside it. These components can also be
containers allowing other components to be nested inside it.
1. Window – It is a freestanding native window on the display. Window
has Frame and Dialog as its subclasses

2. Frame – A frame is a window with a title and resizing corners.

3. Dialog – A Dialog does not have a menu bar. Although u can move it,
you cannot resize it.

4. Panel – It is contained inside another container of inside a web


browser’s window. Panel identifies a rectangular area into which you
must place other components. You must place Panel into a Window
or subclass of window to be displayed.

- Incase u are not using the default layout managers associated with each
container, we must ourselves place the components using the 3 methods –
setLocation(), setSize() and setBounds().

- The layout manager can override your decision. If you must control the size
or position of components in such a way that cannot be done using the
standard layout managers, you can disable the layout manager by issuing
the following method call in your container

Con.setLayout (null); after this u are responsible for the positioning of the
components.

The methods of the class Container are:

Sr. No Method Description

1 Component add (Component c) Adds the specified component to


the end of this container

2 Component add (Component c, Adds the specified component to


int pos) this container at the given position.
Here the number would be –1 to
insert at the end

4 int getComponentCount () Gets the number of components in


the container.

5 Component getComponent (int n) Gets the specified Component

6 LayoutManager getLayout () Gets the container’s


LayoutManager

7 void remove (Component c) Remove the specified Component


8 void removeAll () Removes all Components

9 void setLayout (LayoutManager Re-Sets the Container’s


m) LayoutManager

Every container is also a Component. In addition to the above methods, the


class Component methods are also available for Container.

Frame

- Inherits from the container and adds components with the add() method.

- By Default, the Frame is invisible and hence always we have to use the
method setVisible(true).

- We have to setSize to the Frame also.

- Has Border Layout as the default layout manager

- Uses the setLayout method to change the default layout manager

Import java.awt.*;

class MyFrame extends Frame


{
public MyFrame(String s)
{
super(s)
}

pvsm
{
MyFrame fr = new MyFrame(“Hello”);
fr.setSize(500,500);
fr.setBackground(Color.blue);
fr.setVisible(true);
{
}

IMP: You will have to set visible to true in the case of Frame as by default it is
set to invisible. You can either use setSize() or Pack() (Which is a method of the
Window class) also.
Frames are capable of generating the following types of window events:
WindowOpened, WindowClosing, WindowClosed, WindowIconified,
WindowDeiconified, WindowActivated, WindowDeactivated.

- Frame class represents an optionally resizable top-level application window


with the titlebar and other platform dependent window decorations

- setTitle () specifies a title.

- setMenuBar () specifies a menu bar

- setCursor () specified a cursor

- Call the pack () method of window to initiate layout management of the


window and set its initial size appropriately.

- Call the show () method of the window to make the Frame appear on the
screen or to bring it to the front of the window stack.

- Call the hide () to remove a frame from the screen.

- Call dispose () method when the frame is no longer needed so that it can
release its window system resources for reuse.

- The constructors for frame are:

Frame () - Constructs a frame


Frame (String title) - Constructs a frame with appropriate title.

- Frames are the top-level windows in which application resides, but


applications and applets can also create additional Frames.

Be default, Java sets the frame’s title to untitled. Alternatively a frame can be
created with a specific title. The following line of code, creates a Frame object
with the title “The Frame has a title”.

Frame f = new Frame(“This has a title”);

setCursor () method - Changing the cursor is easy to accomplish with a Java


Frame object. The setCursor () method can be used to change the default
cursor to any of the following pre-defined cursors. The following code creates
Frame object with a crosshair cursor:

Frame f = new Frame (“Frame with a crosshair cursor”);


f.setCursor (Frame.CROSSHAIR_CURSOR);
The following table lists the methods of Frame class:

Sr. Method Description


No

1. int getCursor Type () Get current cursor type

2. MenuBar getMenuBar () Gets menu bar for Frame

3. String getTitle () Gets Frame title.

4. boolean isResizable () Determine if the Frame is resizable

5. void setCursor (int Sets the Frame’s Cursor to the specified


cursorType) shape

6. void setMenuBar (MenuBar Sets menu bar object


mb)

7. void setTitle (String title) Sets title for Frame to given title

An applet that creates Frames at initialization

import java.awt.*;
import java.lang.*;
import java.applet.Applet;

// This applet illustrates how Frames work


// with basic Applet methods
public class AppletBasics extends Applet {
Frame f;
// Called once and only once upon
// applet initialization
public void init() {
System.out.println("In Applet init. Create frame!");
// Create a frame and make it visible...
f = new Frame("Applet Basics test!");
f.resize(300,200);
f.SetVisible(true);
}

// Applet destroyed. Browser probably shutting down...


public void destroy() {
// Destroy the frame
f.dispose();
System.out.println("In applet destroy!");
}
}

Frame's behavior is curious. If you leave the page where the Frame was
created, the Frame will still be active and visible. This may or may not be the
behavior you want. Furthermore, if you remove the dispose () method from the
destroy call, you can get some downright undesirable behavior. In some
browsers, you could create multiple instances of the frame by reopening its
location reference.

An applet that displays the frame only when you are on the applet's page

import java.awt.*;
import java.lang.*;
import java.applet.Applet;

// This applet illustrates how Frames work


// with basic Applet methods
public class AppletBasics extends Applet {
Frame f;
// Called once and only once upon
// applet initialization
public void init() {
System.out.println("In Applet init. Create frame!");
// Create a frame and make it visible...
f = new Frame("Applet Basics test!");
f.resize(300,200);
}

// Move the show to the start method so the Frame


// disappears when you leave the page...
public void start() {
System.out.println("In applet start!");
f.setVisible(true);
}

// Hide the frame when you leave the page...


public void stop() {
System.out.println("In applet stop!");
f.hide();
}

// Applet destroyed. Browser probably shutting down...


public void destroy() {
f.dispose();
System.out.println("In applet destroy!");
}
}

PANELS

- Panel is a container that does not have its own window. It is contained
within some other container.

- The Panel class is a subclass of Container that provides a rectangular


container for other GUI components. This technique is perfect for groups of
controls like radio buttons or checkboxes, because it keeps the group of
controls together.

- Panel can also have another Panel inside it.

- Applet is a subclass of Panel and thus Applets are displayed in a Panel that
is contained within a web browser or applet viewer.

- The default LayoutManager for a Panel is FlowLayout.

- To construct a Panel you can use the following constructors:

Panel () - Creates a new Panel


Panel ( LayoutManager layout) - Creates a Panel with the specified
LayoutManager

- Very Important: Allows subpanels to have their own layout managers

- Adds components with the add () method.

class FrameWithPanel extends Frame


{
public FrameWithPanel(String s)
{
super(s);
}

PVSM
{
FrameWithPanel fr = new FrameWithPanel(“Panel inside a Frame”);
Panel pan = new Panel();
fr.setSize(200,200);
fr.setBackGround(Color.blue);
fr.setLayout(null); // override the default layout manager
pan.setSize(100,100);
pan.setBackground(Color.Yellow);

fr.add(pan);
fr.setVisible(true);
}
}

Layout Managers

Flow Layout –

- Maintains the preferred size of components

Constructor Summary
FlowLayout()
Constructs a new Flow Layout with a centered alignment and a default
5-unit horizontal and vertical gap.
FlowLayout(int align)
Constructs a new Flow Layout with the specified alignment and a default
5-unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap)
Creates a new flow layout manager with the indicated alignment and the
indicated horizontal and vertical gaps.

The value of along must be FlowLayout.LEFT, RIGHT, CENTER

import java.awt.*;

class Ex
{
Frame f
Button b1;
Button b2;

public void go()


{

f.new Frame(“FlowLayout Example”);


f.setLayout(new FlowLayout());
b1 = new Button(“First Button”);
b2 = new Button(“Second Button”);

f.add(b1);
f.add(b2);
f.pack();
f.setVisible(true);
}

PSVM
{
Ex a = new Ex();
a.go();
}
}

import java.awt.*;
import java.applet.Applet;

public class myButtons extends Applet {


Button button1, button2, button3;
public void init() {
button1 = new Button("Ok");
button2 = new Button("Open");
button3 = new Button("Close");
add(button1);
add(button2);
add(button3);
}
}

BORDER Layout

- This is the default layout manager for Frame and Dialog. It has five distinct
areas: North, South, East, West and Center. It is indicated by
BorderLayout.NORTH and so on.

- The second way to add components in BorderLayout is by using the add


(String position e.g. “North”, Component c).

- The relative positions of the buttons do not change, as the window is


resized. So it partically allows for preferred size.

- Incase no position is mentioned, then by default it is inserted into CENTER.

When adding a component to a container with a border layout, use one of these
five constants, for example:
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(new Button("Okay"), BorderLayout.SOUTH);

As a convenience, BorderLayout interprets the absence of a string specification


the same as the constant CENTER:

Panel p2 = new Panel();


p2.setLayout(new BorderLayout());
p2.add(new TextArea()); // Same as p.add(new TextArea(),

import java.awt.*;
import java.applet.Applet;

public class buttonDir extends Applet {


public void init() {
setLayout(new BorderLayout());
add(new Button("North"), BorderLayout.NORTH);
add(new Button("South"), BorderLayout.SOUTH);
add(new Button("East"), BorderLayout.EAST);
add(new Button("West"), BorderLayout.WEST);
add(new Button("Center"), BorderLayout.CENTER);
}
}

VERY IMP: Spellings and Capitalisation are important.

- You can add only a single component to each of the 5 regions of the
BorderLayot manager and if u add more than one, only the one
added last is visible.

Constructor Summary
BorderLayout()
Constructs a new border layout with no gaps between components.
BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between
components.

Example

Create a Frame with border layout


Create 5 bottons
add them to the Frame

f.add(b1, BorderLayout.NORTH) and so on OR

f.add(“center”,”b1”);

Individual Components

Labels

- Labels are effectively text strings that you can use to label other UI
components.

- The advantage that a label has over an ordinary text string is that it follows
the layout of the given panel and you do not have to worry about repainting
it every time the panel is redrawn. Labels also can be easily aligned within a
panel, enabling you to attach labels to other UI components without
knowing exact pixel position.

To create a label, one of the following constructors are used:

Label () - Creates an empty label


Label (String t) - Creates a label with the given text string and
aligned left
Label (String t int alignment - Creates a label with the given text string and
the given alignment.

The available alignments are stored in class variables in Label, making them
easier to remember. Label.RIGHT, Label.LEFT, Label.CENTER. You can add a
Label with the following command.

add(new Label(“Hello”,Label.CENTER));

Once you have a label object, you can use methods defined in the Label class
to get and set the values of the text as shown in table.

Sr. No Method Action

1 String getText() Returns a String containing the labels text

2 void setText(String) Changes the text of this label.

3 int getAlignment () Returns an integer representing the


alignment of this label and the same is
0 is for Label.LEFT, 1 is for Label.CENTER
and 2 is for Label.RIGHT.

Button

- The Button is the simples UI components that trigger some action in your
interface when they are pressed.

- They are usually used for Ok and Cancel buttons in dialog box.

To create a button, one of the constructors used are:

Button () - Creates an empty button with no label.


Button (String t) - Creates a button with the given string object
as a label.

Once you have a button object, you can get the value of the button’s label by
using the getLabel () method and set the label using the setLabel(String)
methods. You can add a button as under:

add(new Button (“OK”)); or by using the following statement

Button b = new Button (“First”);


add(b);

When a Button is pushed, it sends an Action Event.

Canvas

- A canvas is a component that has no default appearance or behavior.

- You can subclass canvas to create drawing regions, work areas,


components and so on.

The default size of the canvas is uselessly small and one way to deal with this
problem is to use a layout manager that will resize the canvas and the other
way to call setSize () on the canvas ourselves. For eg.

Canvas c = new Canvas


c.setBackground (Color.red)
c.setSize (100,50)

Checkbox
- Checkboxes are user interface components that have two states on and off,
checked and unchecked etc.

- Unlike Buttons, Checkboxes usually do not trigger direct action in an UI, but
instead are used to indicate optional features of some action.

- Checkboxes can be used in two ways:

a) Non-Exclusive, meaning that given a series of checkboxes,


any of them can be selected.
b) Exclusive meaning that within one series, only one checkbox
can be selected at a time.

The latter kinds of checkboxes are called radio buttons or checkbox groups and
non-exclusive checkboxes can be created by using the Checkbox Class.

To create a Checkbox,

Checkbox () - creates an empty checkbox, unselected.


Checkbox (String t) - creates a checkbox with the string as a label.
Checkbox (String t - creates a checkbox that is either selected or
boolean b unselected based on whether the boolean
CheckboxGroup c condition is true or false

If you do not specify an initial input, the default is false.

The methods of Checkbox are:

Sr. No Method Action

1 String getLabel () Returns a string containing the


checkboxes label

2 boolean setLabel (String t) Changes the text of the checkboxes label

3 boolean getState () Returns true or false, based on whether


the checkbox is selected or not

4 void setState (boolean b) Changes the checkboxes state to be


selected or unselected

5 addItemListener Adds the given item listener to receive


(ItemListener) item events from this checkbox.

Checkboxes send Item Events when they are selected.


CheckboxGroup

- It is very important to note that this is not a UI component.

- However it can be used to create an association between collections of


Checkbox components. When you instantiate a CheckboxGroup object and
use it to create a set of Checkbox controls. only one of those Checkbox
controls can be selected at a time.

- To create a series of Checkbox controls, first create an instance of


CheckboxGroup.

CheckboxGroup c = new CheckboxGroup();

Then create and add the individual checkboxes using the group as the second
argument and whether or not that checkbox is selected (only one in the series
can be selected).

add (new Checkbox (“System Analyst”, c, false);


add (new Checkbox (“System Auditor”, c, false);
add (new Checkbox (“System Manager”, c, false);

There are two methods in CheckboxGroup and they are:

getSelected Checkbox () - Gets current selected check box

setSelected Checkbox () - Sets the current choice to the specified


Checkbox.

Choice

- The Choice class encapsulates a drop down choice list component.

- The choice component allows a user to select one of the several options or
items in one place.

- To create a choice list, create a instance of the Choice class and then use
addItem () method to add individual items to it in the order in which they
should appear.

Choice c = new Choice();

c.addItem (“Singapore”);
c.addItem (“Bombay”);
The class Choice provides methods that allow you to access or set the currently
selected item in the list. The methods are:

Sr. No Method Description

1 void add (String s) Adds an item to the control

2 int getItemCount () Gets number of items in the control

3 String getItem ( int index) Gets String at specified index in


Choice control

4 int getSelectedIndex () Gets index of currently selected item.

5 void select (int item) Selects item at given position

6 String select (String s) Selects item with specified text

7 addItemListener Adds the given item listener to receive


(ItemListener) item events form this choice.

8 insert (String, int) Inserts the item into this choice at the
specified position.

Choices, like check boxes send Item events when they are selected.

Você também pode gostar