Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

AWT (Abstract Window Toolkit)

            AWT (Abstract Window Toolkit)

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.
AWT Packages
AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of 737 classes as of JDK 1.8). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.
The java.awt package contains the core AWT graphics classes:
GUI Component classes, such as Button, TextField, and Label,


GUI Container classes, such as Frame and Panel,

Layout managers, such as FlowLayout, BorderLayout and GridLayout,
Custom graphics classes, such as Graphics, Color and Font.
The java.awt.event package supports event handling:
Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
Event Listener Interfaces, such as ActionListener, MouseListener, KeyListener and WindowListener,
Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and WindowAdapter.
 
Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces



Sr.No.

Event Classes

Listener Interfaces


ActionEvent

ActionListener


MouseEvent

MouseListener and MouseMotionListener


MouseWheelEvent

MouseWheelListener


KeyEvent

KeyListener


ItemEvent

ItemListener


TextEvent

TextListener


AdjustmentEvent

AdjustmentListener


WindowEvent

WindowListener


ComponentEvent

ComponentListener


ContainerEvent

ContainerListener


FocusEvent

FocusListener





Interface

Description

Methods

ActionListener 

Defines one method to receive action events.

void actionPerformed(ActionEvent ae)

AdjustmentListener 

Defines one method to receive adjustment events.

void adjustmentValueChanged(AdjustmentEvent ae)

ComponentListener 

Defines four methods to recognize when a component is hidden, moved, resized, or shown.

void componentResized(ComponentEvent ce)

void componentMoved(ComponentEvent ce)

void componentShown(ComponentEvent ce)

void componentHidden(ComponentEvent ce)

ContainerListener 

Defines two methods to recognize when a component is added to or removed from a container.

void componentAdded(ContainerEvent ce)

void componentRemoved(ContainerEvent ce)

FocusListener 

Defines two methods to recognize when a component gains or loses keyboard focus.

void focusGained(FocusEvent fe)

void focusLost(FocusEvent fe)


ItemListener 

Defines one method to recognize when the state of an item changes.

void itemStateChanged(ItemEvent ie)


KeyListener 

Defines three methods to recognize when a key is pressed, released, or typed.

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)

MouseListener 

Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released.

void mouseClicked(MouseEvent me)

void mouseEntered(MouseEvent me)

void mouseExited(MouseEvent me)

void mousePressed(MouseEvent me)

void mouseReleased(MouseEvent me)

MouseMotionListener 

Defines two methods to recognize when the mouse is dragged or moved.

void mouseDragged(MouseEvent me)

void mouseMoved(MouseEvent me)

TextListener 

Defines one method to recognize when a text value changes.

void textChanged(TextEvent te)


WindowFocusListener 

Defines two methods to recognize when a window gains or loses input focus.

void windowGainedFocus(WindowEvent we)

void windowLostFocus(WindowEvent we)

WindowListener 

Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened,

void windowActivated(WindowEvent we)

void windowClosed(WindowEvent we)

void windowClosing(WindowEvent we)

void windowDeactivated(WindowEvent we)

void windowDeiconified(WindowEvent we)

void windowIconified(WindowEvent we)

void windowOpened(WindowEvent we)

Steps to perform Event Handling



Following steps are required to perform event handling:

Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
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:
java.awt.FlowLayout
java.awt.BorderLayout
java.awt.GridLayout
java.awt.GridBagLayout
java.awt.CardLayout
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.


FlowLayout(int align, int hgap, int vgap):
 creates a flow layout with the given alignment and the given horizontal and vertical gap.
import java.awt.*;
import java.applet.*;
/*<applet code=FlowDemo width=400 height=500></applet>*/
public class FlowDemo extends Applet
{
Button b1,b2,b3,b4;
Label l;
public void init()
{

setLayout(new FlowLayout());



l=new Label("Hii I'm Label");
b1 = new Button("One");
b2= new Button("Two");
b3 = new Button("Three");
b4 = new Button("Four");

add(b1);



add(b2);
add(l);
add(b3);
add(b4);
}
}
 
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:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.


 

borderlayout (1).jpg
import java.awt.*;
import java.applet.*;
/*<applet code=BorderDemo width=400 height=500></applet>*/
public class BorderDemo extends Applet
{
Button b1,b2,b3,b4;
TextField t;
public void init()
{
setLayout(new BorderLayout());
t=new TextField(40);
b1 = new Button("One");
b2= new Button("Two");
b3 = new Button("Three");
b4 = new Button("Four");

add(b1,BorderLayout.SOUTH);



add(b2,BorderLayout.NORTH);
add(t,BorderLayout.CENTER);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
}
}
Java GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.


GridLayout(int rows, int columns, int hgap, int vgap):
 creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.
import java.awt.*;
import java.applet.*;
/*<applet code=GridDemo width=400 height=500></applet>*/
public class GridDemo extends Applet
{
Button b1,b2,b3,b4;
TextField t1,t2;
Label l1,l2;
public void init()
{
setLayout(new GridLayout(3,3));
l1=new Label("Enter First number");
t1=new TextField(20);
l2=new Label("Enter second number");
t2=new TextField(20);

b1 = new Button("+");
b2= new Button("-");
b3 = new Button("*");
b4 = new Button("/");

add(l1);



add(t1);
add(l2);
add(t2);

add(b1);
add(b2);
add(b3);
add(b4);
}
}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size.
You can set the following GridBagConstraints instance variables:

gridxgridy



Specify the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0. 


ipadxipady



Specifies the internal padding: how much to add to the size of the component. The default value is zero. The width of the component will be at least its minimum width plus ipadx*2 pixels, since the padding applies to both sides of the component. Similarly, the height of the component will be at least its minimum height plus ipady*2 pixels.


gridwidthgridheight



Specify the number of columns (for gridwidth) or rows (for gridheight) in the component's display area. These constraints specify the number of cells the component uses, 
not the number of pixels it uses. The default value is 1. 
Note: GridBagLayout does not allow components to span multiple rows unless the component is in the leftmost column or you have specified positive gridx and gridy values for the component.
weightxweighty
Specifying weights is an art that can have a significant impact on the appearance of the components a GridBagLayout controls. Weights are used to determine how to distribute space among columns (weightx) and among rows (weighty); this is important for specifying resizing behavior.
Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container.
Generally weights are specified with 0.0 and 1.0 as the extremes: the numbers in between are used as necessary. Larger numbers indicate that the component's row or column should get more space. For each column, the weight is related to the highest weightxspecified for a component within that column, with each multicolumn component's weight being split somehow between the columns the component is in. Similarly, each row's weight is related to the highest weighty specified for a component within that row. Extra space tends to go toward the rightmost column and bottom row.
fill
Used when the component's display area is larger than the component's requested size to determine whether and how to resize the component. Valid values (defined as GridBagConstraints constants) include NONE (the default), HORIZONTAL (make the component wide enough to fill its display area horizontally, but do not change its height), VERTICAL (make the component tall enough to fill its display area vertically, but do not change its width), and BOTH (make the component fill its display area entirely).
insets
Specifies the external padding of the component -- the minimum amount of space between the component and the edges of its display area. The value is specified as an Insets object. By default, each component has no external padding.

anchor



Used when the component is smaller than its display area to determine where (within the area) to place the component. Valid values (defined as GridBagConstraints constants) are CENTER (the default), PAGE_START, PAGE_END, LINE_START,LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START.

import java.awt.*;
import java.applet.*;
/*<applet code=GridBagDemo width=400 height=500></applet>*/
public class GridBagDemo extends Applet
{
public void init()
{
            GridBagConstraints gbc = new GridBagConstraints();  
            setLayout(new GridBagLayout());            
         
     gbc.fill = GridBagConstraints.HORIZONTAL;  
     gbc.gridx = 0;  
     gbc.gridy = 0;  
//gbc.weightx=1.0;
     add(new Button("Button One"), gbc);  
    
gbc.gridx = 1;  
     gbc.gridy = 0;  
gbc.weighty=0.9;
     add(new Button("Button two"), gbc);  

     gbc.fill = GridBagConstraints.HORIZONTAL;  



    
gbc.ipady = 20;  
     gbc.gridx = 0;  
     gbc.gridy = 1;  
     add(new Button("Button Three"), gbc);  

     gbc.gridx = 1;  



    
gbc.gridy = 1;  
// gbc.insets = new Insets(10,10,10,10); 
     add(new Button("Button Four"), gbc);  
    
gbc.fill = GridBagConstraints.HORIZONTAL;  
gbc.gridx = 0;  
     gbc.gridy = 2;  
     gbc.gridwidth = 2;  
gbc.ipady = 40;  
     add(new Button("Button Five"), gbc);  
}
}
Java CardLayout
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
CardLayout(): creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.


Commonly used methods of CardLayout class

public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given container.


public void first(Container parent):
 is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.


public void show(Container parent, String name):
 is used to flip to the specified card with the given name.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
hierarchy of awt
Containers and Components
AWT_ContainerComponent.png
There are two types of GUI elements:
Component: Components are elementary GUI entities, such as Button, Label, and TextField etc.
Container: Containers, such as Frame, Applet, Dialog and Panel, are used to hold components in a specific layout (such as FlowLayout or GridLayout). A container can also hold sub-containers.


In the above figure, there are three containers: a Frame and two Panels. A Frame is the 
top-level container of an AWT program. A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close buttons), an optional menu bar and the content display area. A Panel is a rectangular area used to group related GUI components in a certain layout. In the above figure, the top-level Frame contains two Panels. There are five components: a Label (providing description), a TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).
 
Top-Level Containers: Frame, Dialog and Applet
Each GUI program has a top-level container. The commonly-used top-level containers in AWT are Frame, Dialog and Applet:
AWT_Frame.png
A Frame provides the "main window" for the GUI application, which has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area. To write a GUI program, we typically start with a subclass extending fromjava.awt.Frame to inherit the main window as follows:
 
An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog has a title-bar (containing an icon, a title and a close button) and a content display area, as illustrated.
An AWT Applet (in package java.applet) is the top-level container for an applet, which is a Java program running inside a browser. Applet will be discussed in the later chapter.


 

Secondary Containers: Panel and ScrollPane
Secondary containers are placed inside a top-level container or another secondary container. AWT also provide these secondary containers:
Panel: a rectangular box under a higher-level container, used to layout a set of related GUI components in pattern such as grid or flow.
ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.


import java.applet.*;

import java.awt.*;
 
Example of Applet:
/*<applet code=MyApplet width=200 height=200 ></applet>*/
public class MyApplet extends Applet
{
public void init()
{
setBackground(Color.green);
}
public void start()
{
System.out.println("Applet started");
}
public void paint(Graphics g)
{
g.drawString("Hello from Java!", 60, 100);
System.out.println("Hey!! I'm in paint");
}
public void stop()
{
System.out.println("Stop called..");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
How to run?
Open command prompt , change to current working directory and type:
javac MyApplet.java
appletviewer  MyApplet.java
 
Example of Frame:
import java.awt.*;
public class FrameDemo extends Frame
{
public FrameDemo() 
{
setTitle("Frame Demo");
     setSize(250, 120);
        setVisible(true);
}
public static void main(String[] args)
{
new FrameDemo() ;
}
}
How to run?
Open command prompt , change to current working directory and type:
javac FrameDemo.java
java FrameDemo
 
AWT Component Classes
AWT provides many ready-made and reusable GUI components in package java.awt. The frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, and Choice, as illustrated below.
 
AWT_Components.png
 
 
 
 
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.

 


AWT GUI Components: 

java.awt.Label
AWT_Label.png
A java.awt.Label provides a descriptive text string. Take note that System.out.println() prints to the system console, NOT to the graphics screen. You could use a Label to label another component (such as text field) or provide a text description.
 Constructors and Methods

Label Constructor or Method Name

Description

Label()

Constructs an empty label.

Label(String text)

Constructs a label with the specified text.

Label(String text, int alignment)

Constructs a label with the specified text and alignment.

int getAlignment()

Gets the label's alignment.

String getText()

Gets the label's text.

void setAlignment(int alignment)

Sets the label's alignment

void setText(String text)

Sets the label's text.

 


java.awt.Button

A java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.
Button Constructors and Methods

Button Methods and Constructors

Description

Button()

No-arg constructor. Creates a button with no label.

Button(String label)

Constructor. Creates a button with the specified label.

String getLabel()

Gets this button's label.

void setLabel (String label)

Sets this button's label.

// Demonstrate Buttons



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 = "";
Label lbl;
Button yes, no, maybe;
public void init() 
{
lbl=new Label();
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
add(lbl);
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.";
}
lbl.setText(msg);
}
}
java.awt.TextField
Text Areas and Text Fields
Text components are components that store and display text which can be selected and altered. Text components support a number of features including text insertion, editing, selection, and deletion.
The text component classes are subclasses of the TextComponent class, which defines attributes and behavior that is applicable to all text components. The TextComponent class supports text selection, caret positioning, text setting, and toggling of the component's editable state because these features are common to both text fields and text areas.
 
TextArea Class Constructors and Methods

TextArea Constructor or Method Name

Description

TextArea()

Constructs a new text area.

TextArea(int rows, int columns)

Constructs a new text area with the specified number of rows and columns.

TextArea(String text)

Constructs a new text area with the specified initial text.

TextArea(String text, int rows, int columns)

Constructs a new text area with the specified initial text, and the specified rows and columns.

void append(String str)

Appends the specified text to the contained text of this text area.

int getColumns()

Gets the number of columns of this text area.

int getRows()

Gets the number of rows in this text area.

void insert(String str, int pos)

Inserts the specified text starting at the indicated position in this text area.

void setColumns(int columns)

Sets the number of columns for this text area.

void setRows(int rows)

Sets the number of rows for this text area.

 



TextField Class Constructors and Methods

TextField Constructor or Method Name

Description

TextField()

Constructs a new text field.

TextField(int columns)

Constructs a new text field with the specified number of columns.

TextField(String text)

Constructs a new text field that initializes the specified text.

TextField(String text, int columns)

Constructs a new text field with the initial text and the number of columns specified.

boolean echoCharIsSet()

Indicates if this text field has an echo character that is currently set.

int getColumns()

Gets the number of columns of this text field.

char getEchoChar()

Gets the echo character currently set on this text area.

void setColumns(int columns)

Sets the number of columns for thistext field.

void setEchoChar(char c)

Sets the echo character to be used by this text field.

void setText(String t)

Sets the text presented by this text field to the specified string.

import java.awt.*;



import java.applet.*;

/*<applet code=TextfieldDemo width=200 height=200></applet>*/
public class TextfieldDemo extends Applet
{
public void init()
{
TextField t1 = new TextField();
TextField t2 = new TextField(40);
TextField t3 = new TextField("I'm Textfield");
t2.setEchoChar('$');
TextArea ta=new TextArea(10,20);
// add labels to applet window
add(t1);
add(t2);
add(t3);
add(ta);
}
}
Check Boxes
A check box is a component that can be either on or off, that is, either selected or not. You toggle a check box's state by clicking on it. 
Checkbox Constructors and Methods

Methods and Constructors

Description

Checkbox()

No-arg constructor. Constructs a check box with no label.

Checkbox(String label)

Constructs a check box with this label.

Checkbox(String label, boolean state)

Constructs a check box with this label and the specified enabled/disabled state.

Checkbox(String label, boolean state, label CheckboxGroup group)

Constructs a check box with this and the specified enabled/disabled state, and belonging to the check box group.

Checkbox(String label, boolean state)

Constructs a check box with this label, CheckboxGroup group, and the specified enabled/disabled state, and belonging to the check box group.

String getLabel()

Gets this check box's label.

Object [] getSelectedObjects()

Gets an array containing the label of this check box's label, or null if it's not selected.

boolean getState()

Gets the enabled/disabled state.

void setLabel(String label)

Sets the label for this check box.

void setState(boolean state)

Sets the enabled/disabled state.

// Demonstrate check boxes.



import java.applet.*;

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

/*<applet code=CheckboxDemo width=800 height=800></applet>*/



public class CheckboxDemo extends Applet implements ItemListener 

{
Label l;
Checkbox c1, c2, c3, c4;
String s="U selected ";
public void init()
{
setLayout(new FlowLayout());
l=new Label();
c1 = new Checkbox("Windows 98/XP", true);
c2 = new Checkbox("Windows NT/2000");
c3 = new Checkbox("Mac");
c4 = new Checkbox("Solaris OS");
add(l);
add(c1);
add(c2);
add(c3);
add(c4);

c1.addItemListener(this); 



c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent e) 
{
if(c1.getState())
s+=c1.getLabel();
if(c2.getState())
s+=","+c2.getLabel();
if(c3.getState())
s+=","+c3.getLabel();
if(c4.getState())
s+=","+c4.getLabel();

l.setText(s);



}
}
 
CheckboxGroup class
The CheckboxGroup class is used to group the set of checkbox.
 
Constructors and Methods

Methods and Constructors

Description

CheckboxGroup() ()


Creates a new instance of CheckboxGroup.

Checkbox getCurrent()


Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().

Checkbox getSelectedCheckbox()


Gets the current choice from this check box group.

void setCurrent(Checkbox box)


Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).

void setSelectedCheckbox(Checkbox box)


Sets the currently selected check box in this group to be the specified check box.


import java.applet.*;



import java.awt.*;

import java.awt.event.*;

/*<applet code=CheckboxGroupDemo2 width=200 height=200></applet>*/




public class CheckboxGroupDemo2 extends Applet implements ItemListener 



{

Label l;
Checkbox c1, c2, c3, c4;
CheckboxGroup cbg;
public void init()
{
l=new Label("Good Morning SYCS...Jag Jaaooo!!!");
cbg = new CheckboxGroup();
c1 = new Checkbox("Bold", cbg, true);
c2 = new Checkbox("Italic", cbg, false);
c3 = new Checkbox("Plain", cbg, false);
c4 = new Checkbox("Bold+Italic", cbg, false);
add(l);
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this); 
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent e) 
{
if(cbg.getSelectedCheckbox()==c1)
l.setFont(new Font("Arial",Font.BOLD,18));
else if(cbg.getSelectedCheckbox()==c2)
l.setFont(new Font("Arial",Font.ITALIC,20));
else if(cbg.getSelectedCheckbox()==c3)
l.setFont(new Font("Arial",Font.PLAIN,16));
else if(cbg.getSelectedCheckbox()==c4)
l.setFont(new Font("Arial",Font.BOLD|Font.ITALIC,22));
}
}
Choices
The Choice class gives you a way to create a pop-up menu of selections. A choice component looks somewhat like a button, but has a distinctive face. Clicking on a choice component drops down a type of menu (in appearance, but not the same as a real menu). You can select one of the elements in the choice object.
 
Choice Class Constructors and Methods

Methods and Constructors

Description

Choice()

No-arg constructor.

void add(String item)

Adds an item to this check box.

void addItem(String item)

Adds an item to this check box.

String getItem(int index)

Gets the name of the item at the specified index.

int getItemCount()

Gets the number of items in this choice.

int getSelectedIndex()

Gets the index of the selected item.

int getSelectedItem()

Gets the name of the selected item.

void select(int pos)

Selects the item in the indicated position.

// Demonstrate Choice lists.



import java.awt.*;

import java.awt.event.*;
import java.applet.*;
/*<applet code=ChoiceDemo width=200 height=200></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 98/XP");



os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
browser.add("Netscape");
browser.add("Chrome");
browser.add("Internet Explorer");
browser.select("Firefox");
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);
}
}
 
Lists
Lists are groups of items that are formatted inside of a kind of scrolling pane. The list can be scrolled up and down in order to see all its elements. The list gives you a window in which to view some subset of the list elements.
Lists can be single selection or multiple selection, which means, respectively, that only one, or multiple items can be selected simultaneously. Selected elements can be retrieved from a list component and used for various purposes by your application.
List Constructors and Methods

List Constructor or Method Name

Description

List()

Creates a new scrolling list.

List(int rows)

Creates a new list with the number of visible rows specified.

List(int rows, boolean multipleMode)

Creates a new list with the number of visible rows and the specified selection mode behavior.

void add(String item)

Adds a new item to the list.

void add(String item, int index)

Adds a new item at the specified position.

void addItem(Sring item)

Adds a new item to the list.

void addItem(String item, int index)

Adds a new item at the specified position.

String getItem(int index)

Gets the item at the specified index.

int getItemCount()

Gets the number of elements in the list

String [] getItems()

Gets an array of the element names.

int getSelectedIndex()

Gets the index of the selected item.

int [] getSelectedIndexes()

Gets a list of items that are all selected.

String getSelectedItem()

Gets the string that represents the text of the selected item.

String [] getSelectedItems()

Gets a list of the strings that represent the selected items.

void remove(int position)

Removes the item at the specified position.

void remove(String item)

Removes the first occurrence of the item that matches the string.

void removeAll()

Removes all items from this list.

void replaceItem(String newValue, int index)

Replaces the item at the specified position with the new item.

void select(int index)

Selects the item at the specified position.

void setMultipleMode (boolean b)

Makes this list use

// Demonstrate Choice lists.



import java.awt.*;

import java.awt.event.*;
import java.applet.*;
/*<applet code=ListDemo width=200 height=200></applet>*/

public class ListDemo extends Applet implements  ActionListener



{

List langs,os;
String msg = "";
public void init()
{
langs = new List(2 , true);
os = new List(3, false);
langs.add("C");
langs.add("C++");
langs.add("Java");
langs.add(".Net");

os.add("Windows");
os.add("Linux");
os.add("Mac");
os.select(1);
add(langs);
add(os);
langs.addActionListener(this);
os.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) 
{
repaint();
}
public void paint(Graphics g) 
{
int indx[];
msg = "Current Languages: ";
indx = langs.getSelectedIndexes();
for(int i=0; i<indx.length; i++)
  msg += langs.getItem(indx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Menus
Menus are elements that are included as members of menu bars. A menu bar can be placed on a frame. The frame manages its location and layout.
Menus display a list of member menu items when clicked. Selecting the menu item usually results in some action performed by the application. These components behave as their counterparts in other window programming environments.
Menus contain menu items. These two elements are defined by the Menu and MenuItem classes. Menu bars are defined by the MenuBar class.
Menu items can be either simple labels, separators--simply horizontal lines that separate menu items--or other menus.
Menu Class Constructors and Methods

Menu Constructor or Method Name

Description

Menu()

Creates a menu.

Menu(String label)

Creates a menu with the specified name.

void add(MenuItem mi)

Adds a menu item to this menu.

void add(String label)

Adds a simple menu item with the specified label to this menu.

void addSeparator()

Adds a horizontal line separator as a menu item.

int getItem(int index)

Gets the menu item with the specified name.

int getItemCount()

Gets the number of items in this menu.

Menus support adding, removing, and inserting menu items that include other menus and separators that help make the menus more readable. You can define a menu to be a "tear-off" menu, which means it will be rendered in a window detached from the frame that contains the menu bar to which the menu belongs.



MenuItem  Constructors and Methods

MenuItem Constructor or Method Name

Description

MenuItem()

Constructs a new menu item.

MenuItem(String label)

Constructs a new menu item with the specified label.

MenuItem(String label, MenuShortcut s)

Constructs a new menu item with the specified label and shortcut.

void deleteShortcut()

Deletes the short cut item associated with this menu item.

String getActionCommand()

Gets this menu item's string that represents a command name.

String getLabel()

Gets this menu item's text label.

void setActionCommand (String command)

Sets the action command string for this menu item.

Most of the behavior that you will use is defined in the Menu and MenuItem classes. However, theMenuComponent class defines the common behavior for all menu related types, includingMenuBars.



 

MenuBar Class Constructors and Methods

MenuBar Constructor or Method Name

Description

MenuBar()

Creates a new menu bar.

Menu add(Menu m)

Adds the specified menu to this menu bar.

int deleteShortcut(MenuShortcut s)

Deletes the specified shortcut.

int getMenuCount()

Gets the number of menus on this menu bar.

void remove(int index)

Removes the menu at the specified index.

void remove (MenuComponent c)

Removes the specified menu component from this menu bar.


import java.awt.*;



import java.awt.event.*;

import java.util.*;

public class MenusDemo extends Frame implements ActionListener



{

   TextArea ta;
MenuBar mb;
Menu file,format;
MenuItem blnk,exit,d,b,i,p;
   public MenusDemo()
   {                     
     mb = new MenuBar();
     file = new Menu("File");
format = new Menu("Format");

blnk = new MenuItem("New");



    
d= new MenuItem("Date");
exit = new MenuItem("Exit");

b = new MenuItem("Bold");



    
i = new MenuItem("Italic");
p = new MenuItem("Plain");

     ta = new TextArea(10, 40);
     ta.setBackground(Color.pink);
                              
file.add(blnk);
file.add(d);
file.addSeparator();
file.add(exit);

format.add(b);



format.add(i);
format.add(p);

     mb.add(file);
mb.add(format);

setMenuBar(mb);
                             
     blnk.addActionListener(this);
     d.addActionListener(this);
     exit.addActionListener(this);

b.addActionListener(this);



    
i.addActionListener(this);
     p.addActionListener(this);

     add(ta);



setVisible(true);
setTitle("Menu Practice");
     setSize(400, 400);
    

                                          



  }
   public void actionPerformed(ActionEvent ae)
   {
if(ae.getSource()==blnk)
ta.setText(" ");  
else if(ae.getSource()==d)
ta.setText("Date is "+new Date());
else if(ae.getSource()==exit)
System.exit(0);
else if(ae.getSource()==b)
ta.setFont(new Font("Verdana",Font.BOLD,20));
else if(ae.getSource()==i)
ta.setFont(new Font("Arial",Font.ITALIC,25));
else if(ae.getSource()==p)
ta.setFont(new Font("Arial",Font.PLAIN,22));
}

public static void main(String args[])

   {

     new MenusDemo();

   }

}

    


AWT (Abstract Window Toolkit) AWT (Abstract Window Toolkit) Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 16, 2022 Rating: 5

No comments:

Powered by Blogger.