Você está na página 1de 22

Windows

- The Windows class provides the base functionality for both the Frame and
Dialog classes.

- The Windows class implements important methods that are used by its
Frame and Dialog subclasses. In most cases, you should not derive new
classes directly from the Window class.

- Use the Window derived classes, Dialog and Frame, because these classes
provide additional functionality.

- Both the Frame and Dialog classes, for example provide a title bar on the
window, whereas the Window class does not provide a title bar.

- The methods are:

a) show () – To make a window object visible, the show () method must


be called. The show () method provided by the Window class is
similar to the show () method that is provided by the Component
class, however the Window class’s show () method causes a hidden
window to come to the forefront of the screen.

b) hide () – The hide () method makes a Window object disappear. The


hide () method, however is not unique to the Window class; it is
inherited from the Component class.

c) dispose () – The dispose () method removes a window from the


screen and releases all the resources that are used by the Window.

d) pack () – The pack () method is usually called after UI components


are added to a window. This ensures that the components contained
in the window are arranged according to the window layout style. This
method is useful when you want to automatically resize a Frame or
Window to accommodate its components.

e) setSize () – The setSize (), provided by the Window class, enables a


program to change the dimensions of a window. It is used to redefine
the width and height of a window. setSize (int width, int height);

f) setLocation () – The setLocation() method provided by the Window


class enables the repositioning of a Window object within a display
area. The method can be used to reposition a window at a new
location, defined by the specified x, y coordinates. setLocation (int x,
int y);
g) setResizable () – Be default, a Window object is user-resizable. This
characteristic can be controlled with the setResizable () method. The
following line of code, for example makes it impossible for a user to
re-size the window. w.setResizable (false);

Dialog

- Dialogs are top-level windows, with a title and a border, typically to take
some input from the user.

- Dialogs do not have Menu Bar

- Dialogs can move, but cannot be resized.

- A dialog must have either a frame or another dialog defined as its owner
when it's constructed. When the owner window of a visible dialog is hidden
or minimized, the dialog will automatically be hidden from the user. When
the owner window is subsequently re-opened, then the dialog is made
visible to the user again.

- The most commonly used constructor for the Dialog is

a) Dialog (Frame f, String title, Boolean name)

FileDialog

- The FileDialog class represents a file open or file save dialog. The
appearance of these dialogs varies greatly from platform to platform.

- A file dialog is modal, this means that input from the dialog’s parent frame
will be directed exclusively to the dialog, as long as the dialog remains
visible on the screen. The dialog is automatically removed when the user
specifies a file or clicks the Cancel button.

The most useful FileDialog constructor has the following form:

FileDialog (Frame parent, String title, int mode)

The dialog’s parent is the frame over which the dialog will appear. The title
string appears in the dialog’s title bar (on most platforms). The mode should be
either FileDialog.LOAD or FileDialog.SAVE.

After the user has specified the file, the name of the file or the directory can be
retrieved with the following methods:

- String getFile()
- String getDirectory()

The code fragment below constructs a file dialog and displays it above frame f.
After the use has specified a file, the file name is retrieved and displayed.

FileDialog fd = new FileDialog (f, “Choose!”, FileDialog.LOAD);


fd.setVisible (true);
System.out.println(f.getFile ());

List

- A scrolling list presents a scrolling list of choices that the user can select
from or scroll, using the up and down arrow that appear at right in the list
control.

- If a list contains more items than it can display, it requires a vertical scroll
bar.

- The three forms of constructors are:

List ()
List (int visiblerows)
List (int visiblerows, boolean select)

- The number of visiblerows dictates the height of a list. The first version do
not specify the number of visible rows and hence the height is dictated by a
layout manager.

- If the version of the third constructor is used and boolean select is true, then
the list supports multiple selection. If multiple selection is not enabled, then
selecting a new item causes the old selected item to be deselected.

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

List l = new List(2,true); // here 2 is the number of visible items.

l.addItem (“Choice 1”);


I.addItem (“Choice 2”);
I.addItem (“Choice 3”);

add(l);

In the above case since only 2 visible rows are there, but the list has 3 items,
and hence a scroll bar is automatically provided to give access to the botton
row.
Lists are used when multiple selection are needed. The methods in the List is:

Sr. Method Description


No

void addItem(String item) Adds item to end of List.

void addItem (String item, int Adds item to a given position in the
index) list

boolean isMultipleMode () Returns true if control allows multiple


selection.

void clear () Clears the list

int getItemCount () Returns the number of items in the list

void remove( int index) Deletes an item from the list

String getItem (int index) Gets item at specified index

int getRows () Get number of visible lines.

int getSelectedIndex () Gets selected index (-1 if no item is


selected)

String getSelectedItem () Gets selected item

int getVisibleIndex () Gets index of item that is visible.

boolean isIndexSelected () Returns true if item at given index is


selected

void replaceItem (String i, int Replaces item at given index


index)

void select (int index) Selects item at given index

void setMultipleMode (boolean Sets if control should allow multiple


b) selections

addActionListener (Action Adds the given action listener to


Listener) receive action event from this list.
Selecting an item in a list causes the list to send a Item event and double
clicking an item sends an Action Event.

ScrollPane

- The ScrollPane can contain a single component, which may be taller or


wider than the scroll pane itself. If the contained component is larger than
the scroll pane, then the default behaviour of scroll pane is to acquire
horizontal and or vertical scroll bars as needed.

- The two constructors are:

a) ScrollPane () : constructs a scroll pane with a default scroll bar


behaviour
b) ScrollPane (int scrollbarPolicy) : constructs a scroll pane with the
specified scroll bar behavior.

If you use the second form of constructor, then the scrollbarPolicy should be
one of the:

ScrollPane.SCROLLBARS_AS_NEEDED - Default

ScrollPane.SCROLLBARS_ALWAYS

ScrollPane.SCROLLBARS_NEVER

The code listed below creates a scroll pane with default (as-needed) scroll bar
behavior. The scroll pane contains a very large button, so the scroll bars will
definitely be needed.

ScrollPane s = new ScrollPane ();

Button b = new Button (“ What a big teeth you have”);


b.setFont (new Font(“Serif”, Font.BOLD, 80));

s.add(b);

Scroll panes send Mouse and MouseMotion Events.

Scrollbar

- Scrollbars are used most often when only a part of an entity (document,
picture etc) can be displayed by the application and one has to scroll to see
the balance.
- The most common placement of scrollbars is to the right and bottom of the
window. The three constructors are:

Scrollbar () - Default vertical Scrollbar


Scrollbar (int orientation) - constructs a scroll bar with the specified
orientation
Scrollbar (int orientation
int initialValue
int sliderSize
int minValue
int maxValue)

For constructors that take a orientation parameter, this value should be one of
the following:

Scrollbar.HORIZONTAL

Scrollbar.VERTICAL

- For the third constructor, the piece of the scrollbar that slides is the slider.
The sliderSize parameter controls the size of the slider but not in pixel units.
The units of the sliderSize parameter are the units defined by the spread
between the minimum and maximum values of the scrollbar.

- For example, consider a horizontal scroll bar whose minimum value is 600
and maximum value is 700. The spread covered by the scrollbar is the
difference between the two numbers or 100. A sliderSize value of 50 would
represent half the spread and the slider would be half the width of the
scrollbar. A sliderSize value of 10 would represent half the spread the slider
would be one-tenth the width of the scrollbar.

- For Example: Scrollbar sb = new Scrollbar (Scrollbar.HORIZONTAL,


625,25,600,700);

- The above line of code creates a Horizontal scroll bar with the range from
600 to 700 and the initial value is 625. The slider size is 25 out of the range
between 700 - 600 so the slider size should be 1/4th the width of the scroll
bar.

Scroll bars generate Adjustment Events

The Scrollbar class methods are as under:

Sr. No Method Description

1. int getMaximum() Gets maximum setting of Scrollbar


2. int getMinimum() Gets minimum setting of Scrollbar

3. int getOrientation () Gets Orientation of Scrollbar

4. int getValue () Gets current value of Scrollbar

5. void setValue () Sets value of Scrollbar to given value

6. addAdjustmentListener Adds new adjustment listener to get


( Adjustment Listener) adjustment events from this scrollbar

An Example:

public class ScrollbarDemo1 extends Applet implements AdjustmentListener


{
Scrollbar x;
Color c;
Font f;
public void init()
{
x = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,72);
f = new Font("Comic Sans MS", Font.BOLD, 10);
c= new Color(0,0,0);
x.addAdjustmentListener(this);
add(x);
}
public void paint(Graphics g)
{
g.setFont(f);
g.setColor(c);
g.drawString("Tanveer",25,100);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
int r = (int) (Math.random() * 1000)/4;
int g = (int) (Math.random() * 1000)/4;
int b = (int) (Math.random() * 1000)/4;

c = new Color(r,g,b);
f = new Font("Comic Sans MS", Font.BOLD, x.getValue());
repaint();
}
/*public void update(Graphics g)
{
paint(g);

}*/
}

TextComponent

- The TextComponent is the superclass of the TextField and TextArea


classes. These classes provide methods that make it possible to get and
set both the full text with the UI component and currently selected text
within the component.

- All the TextComponent methods are available for both the TextField and
TextArea classes.

The following methods enable you to query and to set the various attributes of a
TextComponent.

Sr. No Methods Description

1. String getSelectedText () Returns the selected text contains in the


TextComponent

2. String getText () Returns the full text contained in the


TextComponent

3. boolean isEditable () Returns a boolean value that indicates


whether this TextComponent is editable.

4. void select (int start, int Selects the text found between the
end) specified start and end character
locations within Text Component.

5. void selectAll () Selects all the Text in the Text


Component

6. void setEditable (boolean Sets whether the TextComponent is


b) editable

7. void setText (String text) Sets the Text of the TextComponent

TextField
- The TextField enables the user to enter information into a TextField.

- The TextField components can be created as empty or with an initial String.

- The TextField components can be defined to have an initial number of


columns.

- If you do not define an initial number of columns, then the layout manager
may use the TextField components initial text value to determine the
TextField component’s appropriate length.

- The TextField class inherits most of its functionality from TextComponent.

- The constructors for the TextField are:

TextField () - Constructs an TextField


TextField (int cols) - Constructs the TextField with specified
number of columns
TextField (String txt) - Constructs the TextField with specified Text
TextField (String t, int cols) - Constructs the TextField with specified Text
and number of columns.

The following methods enable you to query and set the various attributes of the
TextField Components:

Sr. No Method Description

8. int getColumns () Returns the number of columns in the


TextField.

9. Dimension Returns the minimum size dimensions


getMinimumSize (int cols) needed for TextField with the specified.

10. Dimension Returns the preferred size dimensions


getPreferredSize (int cols) needed for the TextField with specified
number of columns.

TextArea

- The TextArea component can contain multiple lines of text.

- Like the TextField component, TextArea components can also be created


either empty or with an initial string.
- TextArea component can be defined with an initial number of rows and
columns.

- The TextArea component inherits most of its functionality from the


TextComponent.

- The following are the TextArea constructors:

TextArea () - Constructs the new TextArea

TextArea ( int rows, int cols) - Constructs the TextArea with the
specified number of rows and columns.

TextArea (String text) - Constructs the TextArea with the


specified String displayed.

TextArea (String t, int rows, int cols) - Constructs the TextArea with specified
text, number of rows and columns.

The following are the important methods in TextArea

Sr. No Method Description

1 void append (String s) Appends the specified text to the end of


the TextArea’s existing text

2 int getColumns() Returns the number of columns in the


TextArea

3 int getRows () Returns the number of rows in the


TextArea

4 insert (String t, int index) Inserts the specified text at the specified
position within the TextArea’s existing
text.

5 Dimension Returns a Dimension Object defining the


getMinimumSize (int minimum size of the TextArea given the
rows, int cols) specified number of rows and columns.

6 Dimension Returns a Dimension Object defining the


getPreferredSize (int preferred size of the specified number of
rows, int cols) rows and columns.

7 void replaceRange Replaces the existing text from the


(String t, int rows, int indicated start to end positions with the
cols) new text specified

- A Dimension object defines the size of an entity, typically in pixels.

- The TextArea class method, getMinimumSize () and getPreferredSize ()


both translate a specified number of rows and columns in a TextArea object
to the appropriate dimensions measured in pixels.

- Frame - Because it implements the MenuContainer interface, it is capable


of working with MenuBar objects.

- The Frame class defines 14 constants that are used to specify different
types of cursors to be used within the frame.

Constructing Menus

Menu Component

MenuBar MenuItem

CheckboxMenu Menu

PopupMenu

- Java provides several classes that allow menu bars to be constructed and
attached to a Frame window.

- These classes are directly descended from the Object class and are not
subclasses of the component class.

- The MenuComponent class is the superclass of the menu-related classes


and provides a common set of methods that are used by its subclasses.

- The MenuComponent class provides a default parameterless constructor,


although objects of this class should not be directly created.

- The getFont() and setFont() methods are used to specify the font to be used
with a MenuComponent object.

- The getParent() method is used to retrieve an object that implements the


MenuContainer interface and contains a specified MenuComponent object.

The MenuBar Class


- The MenuBar class implements a menu bar that is attached to a Frame
window.

- It provides a default parameterless constructor and several access methods


for adding and removing Menu objects from the menu bar.

- It also provides methods that are used to return the current number of
menus and to get and set a special help menu.

The MenuItem Class

- The MenuItem class is used to implement items that may be selected from
a pull-down menu.

- The Menu and CheckboxMenuItem classes extend it.

- The MenuItem class implements items that can be selected from a pull-
down menu.

- Because the Menu and CheckboxMenuItem classes subclass it, it provides


the capability for objects of these classes to be selected from a pull-down
menu.

- This allows multiple levels of menus to be implemented.

- The MenuItem class provides a single constructor that takes a String object
as a parameter. The String object is used as the label of the menu item.

The Menu Class

- The Menu class implements a single pull-down menu that is attached to a


menu bar or other menu.

- It provides two constructors that allow the menu's label to be specified and
determine whether it is to be implemented as a tear-off menu.

- It also provides methods that are used to add or remove menu items, add
menu separators, count the number of items in the menu, and determine
what menu item is currently selected.

The CheckboxMenuItem Class

- The CheckboxMenuItem class is used to implement menu items that may


be checked on or off.
- It provides a single constructor that contains the label to be used with the
checkbox menu item.

- The setState() and getState() methods are used to determine the checked
state of the menu item.

MenuComponent class methods

Sr. Methods Description


No

1 MenuContainer getParent () Gets a reference to the container that


holds this menu component.
2 Font getFont () Gets the current font used to draw menu
item
3 setFont () Sets the font used to draw menu text.

MenuBar Class methods

Sr. Methods Description


No

1 add (Menu m) Adds the specified menu to menu bar

2 int countMenu () Returns the number of menus in the


menubar

3 Menu getHelpMenu () Returns a reference to the designated


help menu.

4 remove (int index) Removes the menu located at the


specified index from the menu bar

5 remove (MenuComponent m) Removes the specified menu


component from the menu bar

6 setHelpMenu (Menu m) Adds the specified menu as the


designated help menu

7 MenuContainer getParent () Gets a reference to the container that


holds this menu component

8 setFont (Font f) Sets the font used to draw menu text.

9 add (MenuItem item) Adds the specified item to the menu


10 add (String label) Creates a menu item with the specified
label and adds it to the menu.

11 addSeperator () Adds a separator item to the menu.

12 int getItemCount () Returns the number of items in the


menu.

13 MenuItem getItem (int index) Returns the specified menu item

14 remove (int index) Removes the specified menu item.

The following are the MenuItem Class methods

Sr. Method Description


No

1 void setEnabled (boolean) Enables the menu item

2 String getLabel () Gets the label associated with the menu


item

3 boolean isEnabled () Returns a value indicating whether the


menu item is enabled

4 setLabel (String label) Sets the label associated with the menu
item to the specified text.

Popup Menus

Popup Menus are usually triggered by the right mouse button and can pop up
anywhere in a window. The constructors to create a popup menu are:

PopupMenu () - Constructs a new popup menu


PopupMenu (String s) - Constructs a new popup menu with the
specified menu

GridLayout Manager

- Constructor has parameters for rows and columns

- Relative position of components does not change


- Size of component changes

- Always Ignores the preferred size

Constructor Summary
GridLayout()
Creates a grid layout with a default of one column per component, in a single
row.
GridLayout(int rows, int cols)
Creates a grid layout with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of rows and columns.

import java.awt.*;
import java.applet.Applet;
public class ButtonGrid extends Applet {
public void init() {
setLayout(new GridLayout(3,2));
add(new Button("1"));
add(new Button("2"));
add(new Button("3"));
add(new Button("4"));
add(new Button("5"));
add(new Button("6"));
}
}

When both the number of rows and the number of columns have been set to
non-zero values, either by a constructor or by the setRows and setColumns
methods, the number of columns specified is ignored. Instead, the number of
columns is determined from the specified number or rows and the total number
of components in the layout. So, for example, if three rows and two columns
have been specified and nine components are added to the layout, then they
will be displayed as three rows of three columns. Specifying the number of
columns affects the layout only when the number of rows is set to zero.

CardLayout

- It treats the interface as a series of cards, one of which you can view at any
one time.

- The add() takes a string as an argument and identifies the panel in the
program.
- The show() switches to a new card on request.

import java.awt.*
import java.awt.event.*

class CardTest implements MouseListener


{
Panel p1,p2,p3
Label, l1,l2,l3

// Declare a cardlayout object to call its methods


CardLayout card;
Frame f;

void go()
{
f = new Frame(“Card Test”);
card = new CardLayout();
f.setLayout(card);

// create the panels that I want to use as cards

p1 = new Panel();
p2 = new Panel();
p3 = new Panel();

// crate a label to attach to each panel and change the color of each panel so
that they can be distinguishable

l1 = new Label(“First”);
p1.setBackground(Color.yellow);
p1.add(l1);

l2 = new Label(“Second”);
p2.setBackground(Color.red);
p2.add(l2);

l3 = new Label(“Third”);
p3.setBackground(Color.cyan);
p3.add(l3);

// set up the event handling here


p1.addMouseListener(this);
p2.addMouseListener(this);
p3.addMouseListener(this);
// add each panel to the card

f.add(p1,”One”);
f.add(p2,”Two”);
f.add(p3,”Three”);

// display the first panel

card.show(f,”One”);
f.setSize(200,200)
f.setVisible(true);

public void mousePressed(MouseEvent e)


{
card.next(f);
}

public void mouseReleased (MouseEvent e){}

public void mouseClicked (MouseEvent e){}

public void mouseEntered (MouseEvent e){}

public void mouseExited (MouseEvent e){}

PVSM
{
CardTest ct = new CardTest();
ct.go();
}
}

CheckBox

- The CheckBox provides a simple on / off input device with a text label
besides it

f = new frame(“Sample Checkbox”);


CheckBox one = new CheckBox(“One”, true);
CheckBox Two = new CheckBox(“Two”, false);
CheckBox one = new CheckBox(“Three”, false);

CheckBoxGroup
- Provides a means to group multiple CheckBox into a mutual exclusion set,
so that only one checkbox in the set has the value of true at any time. The
Checkbox with the value true is the current selected CheckBox. This is
known as Radio Button.
- Will have to give another parameter in the constructor for the
CheckBoxGroup.

Choice

- This provides a simple select one from this list type of input

f = new Frame(“Sample Choice”);

Choice = new Choice();


Choice.addItem(“First”);
Choice.addItem(“Second”);
Choice.addItem(“Third”);
Choice.addItem(“Fourth”);

- When u click on a choice, it displays a list of items that have been added to
it. The items added are string objects.

Canvas

- It provides a blank space. It has a preferred size of zero by zero, unless u


specify a size using the setSize().
- You can use the space to draw, write text, or receive keyboard or mouse
input.
- To receive key events in the canvas, it is necessary to call the
requestFocus() method of the Canvas. If this is not done, it is generally not
possible to direct the keystrokes to Canvas and it goes to another
component or perhaps lost entirely.

class MyCanvas extends Canvas implements KeyListener


{
int index;
Color c[] = {Color.red, Color.green, Color.blue};

public void paint(Graphics g)


{
g.setColor(c[index]);
g.fillRect(o,0,getSize().width, setSize().height);

}
public void keyTyped(KeyEvent e)
{
index ++;
if(index == c.length)
{
index = ;
}
repaint();
}

// other unused KeyListener methods

public void keyPressed (KeyEvent e) {}

public void keyReleased (Key Event e) {}

PVSM
{
Frame f = new Frame(“This is to show example of Canvas”)’
MyCanvas m = new MyCanvas()’
m.setSize(150,150);
f.add(m, BorderLayout.CENTER);

m.requestFocus();
m.addKeyListener(m);

f.pack();
f.setVisible();
}
}

IMP: Labels is also not usually expected to handle events, but can do so in the
same manner as a canvas by calling requestFocus();

TextField

TextField tf = new TextField(“Single Line”, 30);

ActionEvent generated

TextArea

TextArea a = new TextArea(“Hello”, 4,30) // here 4 is the rows and 30 is the


column characters

Both TextArea and TextField as subclasses of TextComponent


Dialog

This is associated with Frames. It is a free-standing window with some


decorations. It different from a Frame in that, you can request a model dialog
which causes it to store all forms of input until it is closed.

ScollPane

- This creates a manages the scroll bars and holds a single component. You
cannot control the layout manager it uses. Instead you can add a Panel to
the scroll pane, configure the layout manager of that panel and place your
components in that panel.
- Generally you do not handle events on the scroll pane, events are handled
through the components that they contain.

sp.add(p)

MENUS

- Menu is different from other components because you cannot add a menu
to a ordinary container and have they laid out by the layout manager
- You can add menu only to a menucontainer.
- You can start a menu tree by putting a menu bar in a Frame using the
setMenuBar() method. From that point you can add menus to the menu bar
and menus or menu items to the menus.
- popup Menus are an exception because they appear as floating windows
and therefore do not require a layout.

- Using the menu bar, you can designate one menu to be the help menu. You
can do this using the method setHelpMenu(Menu).

- You must add the menu to be treated as the Help menu to the menu bar, it
is then treated in the same way as the help menu for the local platform.

MenuBar

MenuBar Component is a horizontal menu. You can add it only to a Frame


object and it forms the root of all menu trees. A Frame can display one MenuBar
at a time. However u can change the MenuBar based on the state of the
program so that different menus can appear at various points.

Frame f
MenuBar mb = new
f.setMenuBar(mb).
The MenuBar does not support listeners. AS part of the normal menu
behaviour, anticipated events that occur in the region of the menu bar are
processed automatically.

The Menu Component provides a basic pull down menu. You can add it either
to a MenuBar or to another Menu.

f = new Frame (“MENU”);

mb = new MenuBar();

m1 = new Menu(“File”)
m2 = mew Menu(“Edit”)
m3 = new Menu(“Help”);

mb.add(m1)
mb.add(m2)
mb.setHelpMenu(m3)
f.setMenuBar(mb)

MenuItem

MenuItem components are the text lead nodes of a menu tree. They are added
to a menu to complete it.

mi1 – new MenuItem(“New”)


mi2 – new MenuItem(“Save”)
mi3 – new MenuItem(“Load”)
mi4 – new MenuItem(“Exit”)

mi1.addActionListener(this;

m1.add(mi1)
m1.add(mi2)
m1.add(mi3)
m1.addSeperator();
m1.add(mi4)

CheckBoxMenu Item

It is a checkable menu item (on or off)

mb = new MenuBar
m1 = new Menu (File)
m2 = Edit
m3 = Help

mb.add(m1)
mb.add(m2)
mb.setHelpMenu(m3)
f.setMenuBar(mb)

mi1 = new MenuItem(“Save);


mi2.addActionListener (this)
m1.add(mi2)

mi5 = new CheckBoxMenuItem(“Persistent”)


m1.add(mi5);

PopUpMenu

This is a standalone menu that can be displayed on any component. You can
add iems or menus to popup menus

Frame f
Button b

PopupMenu p = new PopupMenu(“Popup”)


MenuItem s = new MenuItem(“Save”);
MenuItem id = new MenuItem(“Load”)

f.add(b,BorderLayout.CENTER);

p.add(s);
p.add(id);
f.add(p).

- For the popup menu to be displayed, you must call the show() method. This
is written in the actionPerformed (ActionEvent e). p.show(10,10). That is the
origin for the x and y coordinates.

IMP” You must add PopUpMenu to a parent component. This is not the same as
adding componets to containers.

Você também pode gostar