Thursday, August 3, 2023

Java Astract Window Toolkit - I

 


Java Astract Window Toolkit - I


    AWT Overview 

The basic idea behind the AWT is that a java window is a set of nested components,starting from the outer most window to the smallest User Interface(UI) component.

Window Fundamentals

The AWT defines window according to a class hierarchy that adds functionality and specificity with each level.the two most common windows are those derived from panel,which is used by applets,and those derived from frame,which creates a standard window.

Component

At the top of the AWT hierarchy is the component class.Component is an abstract class that encapsulates all of the attributes of a visual component.

Containers

Containers are generic AWT components that can contain other components,including other containers

PANEL

The Panel class is a concrete subclass of Container.

Canvases

A canvas is a simple drawing surface.

Frame

Frame encapsulates what is commonly thought of as a "window". It is a subclass of window and  has a title bar,menubar,borders,and resizing corners.

UI Components

These can include buttons,lists,simple popup menus,checkboxes, text field,and other typical elements of a user interface.

Labels

The simplest form of UI components is the label.

Constructors

Description

Label()

Creates an empty label,with its text aligned left

Label(string)

Creates a label with the given text string,also aligned left

Label(string,int)

Creates a label with the given text string and the given alignment.the available alignments

The  available alignments are stored in class variables in label,making them easier to remember Label.RIGHT,label.LEFT,and

Label.CENTER

 

add(newLabel("aligned left"));

add(newLabel("aligned center",Label.CENTER));

add(newLabel("aligned right",Label.RIGHT));

Method

Action

getText()

Returns a string containing label's text

getText(string)

Changes the text of this label

getAlignment

Returns an integer representing the alignment of this label: 0 is label.LEFT. 1 is label.CENTER,2 is Label.RIGHT

setAlignment(int)

Changes the alignment of this label to the given integer-use the class variables above

 

Illustrating Label Class

File name: Labels.java

import java.applet.*;

import java.awt.*;

/*<applet code="Labels" width=200 height=200>

</applet>

*/

public class Labels extends Applet{

public void init(){

String s="Hello World";

Label L1=new Label(s,Label.LEFT);

add(L1);

Label L2=new Label(s,Label.CENTER);

add(L2);

Label L3=new Label(s,Label.RIGHT);

add(L3);

}

}

 

Output

 



 

Buttons

v      Button()creates an empty button with no label

v      Button(string)creates a button with the given string object as a label

Method

Description

addActionListener(ActionListener1)

Adds the specified action

Listener to receive action events from the corresponding button

getActionCommand()

Returns the command name of the action event fired bythecorresponding button.

getLabel()

Returns the label of the corresponding button

paramString()

Return the parameter string representing the state ofthecorresponding

Button.

setLabel(Stringlabel)

Sets the label of the button to the value specified

Handling Buttons

File name: ButtonDemo.java

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ButtonDemo" width=250 height=150>

</applet>

*/

public class ButtonDemo extends Applet implements ActionListener{

String msg=" ";

Button yes,no,maybe;

public void init(){

yes=new Button("Yes");

no=new Button("No");

maybe=new Button("Undecided");

add(yes);

add(no);

add(maybe);

yes.addActionListener(this);

no.addActionListener(this);

maybe.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

String str=ae.getActionCommand();

if(str.equals("Yes")){

msg="You pressed Yes";

}

else if(str.equals("No")){

msg="You pressed No";

}

else{

msg="You Pressed Undecided";

}

repaint();

}

public void paint(Graphics g){

g.drawString(msg,6,100);

}

}

 

Output

 






Checkboxes

A check box is a control that is used to turn an option on or off.

Checkboxes can be used in two ways:

v      Nonexclusive,meaning that given a series of checkboxes,any of them can be selected.

v      Exclusive,meaning that within one series,only one checkbox can be selected at a time.

 

Constructor

Action

Checkbox()

Creates an empty checkbox,unselected .      

Checkbox(String)

Create a checkbox with the given string as a label

Checkbox

Creates a checkbox that is either selected or unselected

(String,null,boolean)

Based on whether the boolean argument is trueor false,respectively

(the null is used as a placeholder for group argument.only radio buttons have groups,as you'll learn in the next section).

 

METHODS

DESCRIPTION

getLabel()

Returnsa strincontaining

This checkbox's label

setLabel(String)

Changes the text of the checkbox's label

getState()

Returnstrueorfalse,based on whether the checkbox

Is selected or not

 

 

setState(boolean)

Changes the checkbok's state to selected (true) or unselected (false)

 

Check Box

File name: CheckboxDemo.java

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="CheckboxDemo" width=250 height=200>

</applet>

*/

public class CheckboxDemo extends Applet implements ItemListener{

String msg="";

Checkbox Win2000,linux,unix,WinMe;

public void init(){

Win2000=new Checkbox("Windows 2000",null,true);

linux=new Checkbox("Linux");

unix=new Checkbox("Unix",null,true);

WinMe=new Checkbox("Mac OS");

add(Win2000);

add(linux);

add(unix);

add(WinMe);

Win2000.addItemListener(this);

linux.addItemListener(this);

unix.addItemListener(this);

WinMe.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie){

repaint();

}

//Display current state of the check boxes

public void paint(Graphics g){

msg="Current state:";

g.drawString(msg,6,80);

msg="Windows 2000:"+Win2000.getState();

g.drawString(msg,6,100);

msg="Linux:"+linux.getState();

g.drawString(msg,6,120);

msg="Unix:"+unix.getState();

g.drawString(msg,6,140);

msg="MacOS:"+WinMe.getState();

g.drawString(msg,6,160);

}

}

 

Output

 




Radio Buttons

CheckboxGroup cbg=newCheckboxGroup();

add(newCheckbox("yes",cbg,true);

add(newCheckbox("no",cbg,false);

Checkbox getSelectedCheckbox()

Void setSelectedCheckbox(Checkbox which) 
Radio Buttons

File name: CBGroup.java

//Demonstrate check box group

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

         <applet code="CBGroup" width=250 height=200>

         </applet>

*/

public class CBGroup extends Applet implements

ItemListener{

            String msg="";

            Checkbox  Win98,linux,unix,WindowsMe;

            CheckboxGroup cbg,cbg1;

public void init(){

         cbg =new CheckboxGroup();

          cbg1 =new CheckboxGroup();  

          Win98 =new Checkbox("Windows 98",cbg,true);

          linux=new Checkbox ("Linux",cbg,false);

          unix = new Checkbox("Unix",cbg1,true);

          WindowsMe = new Checkbox("Windows ME",cbg1,false);

           add(Win98);

           add(linux);

           add(unix);

           add(WindowsMe);

           Win98.addItemListener(this);

           linux.addItemListener(this);

           unix.addItemListener(this);

           WindowsMe.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie){

              repaint();

}

//Display current state of the check boxes.

public void paint (Graphics g){

             msg= "Selection 1:";

             msg +=cbg.getSelectedCheckbox().getLabel();

             g.drawString(msg,6,100);

             msg ="Selection2:";

             msg +=cbg1.getSelectedCheckbox().getLabel();

             g.drawString(msg,6,120);

             }

}

  

Output


 

Choice Menu

Choice c=new Choice();

c.addItem("Apples");

c.addItem("Oranges");

c.addItem("Strawberries");

c.addItem("Blueberries");

c.addItem("Bananas");

Method

Action

getItem(int)

Returns the string item at the given position (itemsinsideachoicebegin at 0,sameasarray)countItems() Return the number of items in the menu.

getSelectedIndex()

Return the index position of the item that's selected

getSelectedItem()

Returns the currently selected item as a string

getItem(intIndex)

Gets the string at the specified index of the corresponding choice menu

getItemCount()

Returns the number of items in the corresponding choice menu

getSelectedIndex()

Gets a representation of the currently selected item

getSelectedItem()

Gets a representation of the current choice as a string

Select(int)

Select the item at the given position

Select(int pos)

Sets the selected item in the corresponding choice menu to be the item at the specified position

Select(string)

Select the item with the given string

Choice Menus

File name: ChoiceDemo.java


import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ChoiceDemo" width=300 height=180>

</applet>

*/

public class ChoiceDemo extends Applet implements ItemListener{

Choice os,browser;

String msg="";

public void init(){

os=new Choice();

browser=new Choice();

os.add("Windows 2000");

os.add("Windows ME");

os.add("Linux");

os.add("Unix");

browser.add("Netscape 1.1");

browser.add("Netscape 2.x");

browser.add("Netscape 3.x");

os.add("MacOS");

browser.add("Internet Explorer 2.0");

browser.add("Internet Explorer 3.0");

browser.add("Internet Explorer 4.0");

browser.add("Lynx 2.4");

browser.select("Netscape 4.x");

add(os);

add(browser);

os.addItemListener(this);

browser.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie){

repaint();

}

public void paint(Graphics g){

msg="Current OS:";

msg+=os.getSelectedItem();

g.drawString(msg,6,120);

msg="Current browser:";

msg+=browser.getSelectedItem();

g.drawString(msg,6,140);

}

}


Output

 


 Lists

 Handling Lists

 File name: ListEvents.java

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="ListEvents" width=400 height=200>

</applet>

*/

public class ListEvents extends Applet implements ActionListener,ItemListener

{

TextArea ta;

public void init()

{

List l=new List();

l.add("Monitor");

l.add("Keyboard");

l.add("Mouse");

l.add("Light Pen");

l.add("Joy Stick");

l.add("Printer");

l.add("Scanner");

l.addActionListener(this);

l.addItemListener(this);

add(l);

ta=new TextArea(10,20);

add(ta);

}

public void actionPerformed(ActionEvent ae)

{

ta.append("ActionEvent:"+ae.getActionCommand()+"\n");

}

public void itemStateChanged(ItemEvent ie)

{

List l=(List)ie.getItemSelectable();

ta.append("Item Event:"+l.getSelectedItem()+"\n");

}

}


Output


 

Scrollbars

Scrollbars are used to select continuous values between a specified minimum and maximum.

Scrollbars may be oriented horizontally or vertically.

Constructors

Action

Scrollbar()

Creates a vertical scrollbar

Scrollbar(int style)

IfstyleisScrollbar.VERTICAL,

a vertical scrollbar is created ,if style is Scrollbar.HORIZONTAL,the scrollbar is horizontal

 

Scrollbar(int style,int initialvalue,int thumbsize,int min,int max)

IfstyleisScrollbar.HORIZONTAL,the scrollbar is horizontal. if style is Scrollbar. VERTICAL, a vertical scrollbar is created.

The constructor, the initial value of the scrollbar is passed in initial value.

The number of units represented by the height of the thumb is passed in thumb size.

The minimum and maximum values for the scroll bar are specified by min and max

 

Scrollbars methods

Method

Action

getMaximum()

Returns the maximum value

getMinimum()

Returns the minimum value

getOrientation()

Returns the Orientation of this scrollbar: 0 is Scrollbar.HORIZONTAL,1 is scrollbar.VERTICAL

getValue()

Returns the scrollbar's current value

setValue(int)

Sets the current value of the scrollbar.

  

Handling Scroll Bars

 

File name: SliderTest.java

import java.awt.*;

/*

<applet code="SliderTest" width=300 height=300>

</applet>

*/

public class SliderTest extends java.applet.Applet{

Label l;

public void init(){

l=new Label("0");

add(l);

add(new Scrollbar(Scrollbar.HORIZONTAL,1,0,1,100));

}

public boolean handleEvent(Event evt){

if(evt.target instanceof Scrollbar){

int v=((Scrollbar)evt.target).getValue();

l.setText(String.valueOf(v));

}

return true;

}

}

  

Output

 


 


 Text Fields

Constructor

Action

TextField()

Creates an empty TextField 0 characters wide

TextField(int)

Creates an empty TextField with the given width in characters.

TextField(string)

Creates a TextField 0 characterswide,initialized

With the given string. TextField(String,int) creates a text field with the given width in characters andcontaining

The given string.if the string is longer than the width,you can select and drag portions of the text within the field and box will scroll left or right

 

TextFields methods

 

Method

Action

getText()

Returns the text this field contains(as a string)

setText(String)

Puts the given text string into the field

getColumns()

Returns the width of this text field

Select(int,int)

Selects thetext between the twointeger positions

(positions startfrom 0)

fselectAll()

Selects all the text in the field

isEditable()

Return true or false based on whether the text is editable or not

setEditable(boolean)

True(thedefault)enables

Text tobe edited;false freezes the text.

getEchoChar()

Return the characters used for masking input

echoCharIsSet()

Return true or false whether the field has a masking character or not

Text Fields

File name: TextFieldDemo.java

//Demonstrate text field.

 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="TextFieldDemo"width=380 height=150>

</applet>

*/

public class TextFieldDemo extends Applet

             implements ActionListener{

             TextField name,pass;

             public void init(){

                          Label namep=new Label("Name:",Label.RIGHT);

                          Label passp=new Label("Password:",Label.RIGHT);

                          name=new TextField(12);

                          pass=new TextField(8);

                          pass.setEchoChar('?');

                          add(namep);

                          add(name);

                          add(passp);

                          add(pass);

                          //register to receive action events

                          name.addActionListener(this);

                          pass.addActionListener(this);

             }

             //User pressed Enter.

             public void actionPerformed(ActionEvent ae) {

                          repaint();

             }

             public void paint(Graphics g) {

                          g.drawString("Name:"+name.getText(),6,60);

                          g.drawString("Selected text in name:"+name.getSelectedText(),6,80);

                          g.drawString("Password:"+pass.getText(),6,100);

             }

}

                         

 Output

 


 

 TextAreas

Constructor

Action

TextArea()

Creates on empty text area 0 rows long and 0 characters wide.given that a text area with no dimensions can't be displayed,you should make sure you change the dimensions of this newtext area before adding it to a panel(or just use the next constructor instead)

         

TextArea(int,int)

Creates an empty text area with the given number of rows and columns(characters).

TextArea(string)

Creates a text area displaying the given string,0 rows by 0 columns

TextArea(string,int,int)

Creates a text area displaying the given stringand with the given dimensions

TextArea(string str, intnumLines,int numchars,int sBars)

Here,num numchars specifiestheheight,inlines

Of the textarea,andnumchars specifies its width,in characters.

Initial text can be specified by str.in the fifth form you can specify the scrollbars that you want the control to have

Handling TextField and Text Area

File name: TextFieldEvents.java

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="TextFieldEvents" width=400 height=200>

</applet>

*/

public class TextFieldEvents extends Applet implements ActionListener,TextListener

{

TextArea ta;

TextField tf;

public void init()

{

tf=new TextField(20);

tf.addActionListener(this);

tf.addTextListener(this);

add(tf);

ta=new TextArea(10,20);

add(ta);

}

public void actionPerformed(ActionEvent ae)

{

ta.append("ActionEvent:"+ae.getActionCommand()+"\n");

}

public void textValueChanged(TextEvent te)

{

ta.setText("TextEvent:"+tf.getText()+"\n");

}

}

 

Output




0 comments:

Post a Comment