Monday, 24 June 2013

24th june 2013

LIST 
import java.awt.*;
import java.applet.*;
/*
<applet code="listdemo.class" width=400 height=400>
</applet>
*/
public class listdemo extends Applet
{
  List ch1,ch2,ch3;
  public void init()
{
 
  ch1=new List();
    ch2=new List(2);
 ch3=new List(2,true);
 ch1.add("mango");
 ch1.add("apple");
 ch1.add("grapes");
 ch1.add("guava");
 ch2.addItem("Internet");
 ch2.addItem("Opera");
 ch2.addItem("mozilla");
 ch3.addItem("train");
 ch3.addItem("bus");
 ch3.addItem("car");
 add(ch1);
 add(ch2);
   add(ch3);

}


}

COMBO BOX 
import java.awt.*;
import java.applet.*;
/*
<applet code="combodemo.class" width=400 height=400>
</applet>
*/
public class combodemo extends Applet
{
  Choice ch1,ch2,ch3;
  Label s,s1;
  public void init()
{   Choice ch=new Choice();
   s=new Label("state");

  ch1=new Choice();
   s1=new Label("course");

    ch2=new Choice(2);

 ch1.add("mango");
 ch1.add("apple");
 ch1.add("grapes");
 ch1.add("guava");
 ch2.addItem("Internet");
 ch2.addItem("Opera");
 ch2.addItem("mozilla");
 add(s);
 add(ch1);
 add(s1);
 add(ch2);


}


}

TEXT AREA \


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="txtdemo.class" width=400 height=400>
</applet>
*/
public class txtdemo extends Applet implements ActionListener
{
     String msg="";
int a,b1,r;
TextField t1,t2,t3;
Label s,s1,s2;

Button add,sub,mul,div;
char OP;
public void init()
{
   //GridLayout gl=new GridLayout (1,2);
//setLayout(gl);
setBackground(Color.pink);
   t1=new TextField(6);
t2=new TextField(6);
t3=new TextField(20);
    s=new Label("First Number");
s1=new Label("Second Number");
s2=new Label("Result");
add=new Button("Add");
sub=new Button("Subtract");
mul=new Button("Multiply");
div=new Button("Divide");

add(s);
add(t1);
add(s1);
add(t2);
        add(add);
add(sub);
add(mul);
add(div);
add(s2);
add(t3);

t1.addActionListener(this);
t2.addActionListener(this);
t3.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
    String str =ae.getActionCommand();
char ch=str.charAt(0);
if (Character.isDigit(ch))
{ t1.setText(t1.getText()+str);
t2.setText(t2.getText()+str);}
else if (str.equals("Add"))
{
   a=Integer.parseInt(t1.getText());
b1=Integer.parseInt(t2.getText());
OP='+';
t1.setText("");
t2.setText("");
}
else if (str.equals("Subtract"))
{
   a=Integer.parseInt(t1.getText());
    b1=Integer.parseInt(t2.getText());
OP='-';
t1.setText("");
t2.setText("");
}
else if (str.equals("Multiply"))
{
   a=Integer.parseInt(t1.getText());
b1=Integer.parseInt(t2.getText());
OP='*';
t1.setText("");
t2.setText("");
}
else if (str.equals("Divide"))
{
   a=Integer.parseInt(t1.getText());
b1=Integer.parseInt(t2.getText());
OP='/';
t1.setText("");
t2.setText("");
}

if (OP=='+')
r=a+b1;
else if (OP=='-')
r=a-b1;
else if (OP=='*')
r=a*b1;
else if (OP=='/')
r=a/b1;
t3.setText(""+r);
}


}



Friday, 21 June 2013

21 june 2013

1.BUTTONS

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="bdemo.class" width=400 height=400>
</applet>
*/
public class bdemo extends Applet implements ActionListener
{
public void init()
{

Button b1=new Button("Red");
Button b2=new Button("Pink");
Button b3=new Button("Blue");
Button b4=new Button("Yellow");
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
     String str =ae.getActionCommand();
if(str.equals("Red"))
{
    setBackground(Color.red);
}
 if(str.equals("Pink"))
{
    setBackground(Color.pink);
}
 if(str.equals("Blue"))
{
    setBackground(Color.blue);
}
 if(str.equals("Yellow"))
{
    setBackground(Color.yellow);
}
}
}

2. CHECKBOX
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="checkdemo.class" width=400 height=400>
</applet>
*/
public class checkdemo extends Applet implements ItemListener
{     String str;
    Checkbox c1,c2;
public void init()
{
  c1=new Checkbox("hockey");
  c2=new Checkbox("football");
  add(c1);
  add(c2);
  c1.addItemListener(this);
  c2.addItemListener(this);
}
   public void itemStateChanged(ItemEvent ie)
   {
       repaint();
  if (c1.getState()==true)
  {
     str="you select "+c1.getLabel();
  }
   if (c2.getState()==true)
  {
     str="you select "+c2.getLabel();
  }
   }
   public void paint(Graphics g)
   {
      g.drawString(str,100,100);
   }
}

3. radio button

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="radio1demo.class" width=400 height=400>
</applet>
*/
public class radio1demo extends Applet implements ItemListener
{   CheckboxGroup cbg;
    Checkbox c1,c2;
String str;
public void init()
{
  c1=new Checkbox("h",cbg,true);
  c2=new Checkbox("f",cbg,false);
  add(c1);
  add(c2);
  c1.addItemListener(this);
  c2.addItemListener(this);
}
   public void itemStateChanged(ItemEvent ie)
   {
       repaint();

   }
   public void paint(Graphics g)
   {
      Checkbox cd=cbg.getSelectedCheckbox();
 str=""+cd.getLabel();
 g.drawString(str,100,100);
   }
}

Thursday, 20 June 2013

20th june 2013

How to Use Buttons, Check Boxes, and Radio Buttons

To create a button, you can instantiate one of the many classes that descend from the AbstractButton class. The following table shows the Swing-defined AbstractButton subclasses that you might want to use:
ClassSummaryWhere Described
JButtonA common button.How to Use the Common Button API and How to Use JButton Features
JCheckBoxA check box button.How to Use Check Boxes
JRadioButtonOne of a group of radio buttons.How to Use Radio Buttons
JMenuItemAn item in a menu.How to Use Menus
JCheckBoxMenuItemA menu item that has a check box.How to Use Menus and How to Use Check Boxes
JRadioButtonMenuItemA menu item that has a radio button.How to Use Menus and How to Use Radio Buttons
JToggleButtonImplements toggle functionality inherited by JCheckBox and JRadioButton. Can be instantiated or subclassed to create two-state buttons.Used in some examples

Note: If you want to collect a group of buttons into a row or column, then you should check out tool bars.
First, this section explains the basic button API that AbstractButton defines — and thus all Swing buttons have in common. Next, it describes the small amount of API that JButton adds to AbstractButton. After that, this section shows you how to use specialized API to implement check boxes and radio buttons.

How to Use the Common Button API

Here is a picture of an application that displays three buttons:
A snapshot of ButtonDemo

Try this: 
  1. Click the Launch button to run the Button Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example
  2. Click the left button.
    It disables the middle button (and itself, since it is no longer useful) and enables the right button.
  3. Click the right button.
    It enables the middle button and the left button, and disables itself.

As the ButtonDemo example shows, a Swing button can display both text and an image. In ButtonDemo, each button has its text in a different place, relative to its image. The underlined letter in each button's text shows the mnemonic — the keyboard alternative — for each button. In most look and feels, the user can click a button by pressing the Alt key and the mnemonic. For example, Alt-M would click the Middle button in ButtonDemo.
When a button is disabled, the look and feel automatically generates the button's disabled appearance. However, you could provide an image to be substituted for the normal image. For example, you could provide gray versions of the images used in the left and right buttons.
How you implement event handling depends on the type of button you use and how you use it. Generally, you implement an action listener, which is notified every time the user clicks the button. For check boxes you usually use an item listener, which is notified when the check box is selected or deselected.
Below is the code from ButtonDemo.java that creates the buttons in the previous example and reacts to button clicks. The bold code is the code that would remain if the buttons had no images.
//In initialization code:
    ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
    ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
    ImageIcon rightButtonIcon = createImageIcon("images/left.gif");

    b1 = new JButton("Disable middle button", leftButtonIcon);
    b1.setVerticalTextPosition(AbstractButton.CENTER);
    b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
    b1.setMnemonic(KeyEvent.VK_D);
    b1.setActionCommand("disable");

    b2 = new JButton("Middle button", middleButtonIcon);
    b2.setVerticalTextPosition(AbstractButton.BOTTOM);
    b2.setHorizontalTextPosition(AbstractButton.CENTER);
    b2.setMnemonic(KeyEvent.VK_M);

    b3 = new JButton("Enable middle button", rightButtonIcon);
    //Use the default text position of CENTER, TRAILING (RIGHT).
    b3.setMnemonic(KeyEvent.VK_E);
    b3.setActionCommand("enable");
    b3.setEnabled(false);

    //Listen for actions on buttons 1 and 3.
    b1.addActionListener(this);
    b3.addActionListener(this);

    b1.setToolTipText("Click this button to disable "
                      + "the middle button.");
    b2.setToolTipText("This middle button does nothing "
                      + "when you click it.");
    b3.setToolTipText("Click this button to enable the "
                      + "middle button.");
    ...
}

public void actionPerformed(ActionEvent e) {
    if ("disable".equals(e.getActionCommand())) {
        b2.setEnabled(false);
        b1.setEnabled(false);
        b3.setEnabled(true);
    } else {
        b2.setEnabled(true);
        b1.setEnabled(true);
        b3.setEnabled(false);
    }
} 

protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = ButtonDemo.class.getResource(path);
    ...//error handling omitted for clarity...
    return new ImageIcon(imgURL);
}

How to Use JButton Features

Ordinary buttons — JButton objects — have just a bit more functionality than the AbstractButton class provides: You can make a JButton be the default button.
At most one button in a top-level container can be the default button. The default button typically has a highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and the user presses the Return or Enter key. Here is a picture of a dialog, implemented in the ListDialog example, in which the Set button is the default button:
In the Java Look & Feel, the default button has a heavy border
You set the default button by invoking the setDefaultButton method on a top-level container's root pane. Here is the code that sets up the default button for the ListDialog example:
//In the constructor for a JDialog subclass:
getRootPane().setDefaultButton(setButton);
The exact implementation of the default button feature depends on the look and feel. For example, in the Windows look and feel, the default button changes to whichever button has the focus, so that pressing Enter clicks the focused button. When no button has the focus, the button you originally specified as the default button becomes the default button again.

How to Use Check Boxes

The JCheckBox class provides support for check box buttons. You can also put check boxes in menus, using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit fromAbstractButton, Swing check boxes have all the usual button characteristics, as discussed earlier in this section. For example, you can specify images to be used in check boxes.
Check boxes are similar to radio buttons but their selection model is different, by convention. Any number of check boxes in a group — none, some, or all — can be selected. A group of radio buttons, on the other hand, can have only one button selected.
Here is a picture of an application that uses four check boxes to customize a cartoon:
NOT a tutorial reader!

Try this: 
  1. Click the Launch button to run the CheckBox Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example
  2. Click the Chin button or press Alt-c.
    The Chin check box becomes unselected, and the chin disappears from the picture. The other check boxes remain selected. This application has one item listener that listens to all the check boxes. Each time the item listener receives an event, the application loads a new picture that reflects the current state of the check boxes.

A check box generates one item event and one action event per click. Usually, you listen only for item events, since they let you determine whether the click selected or deselected the check box. Below is the code from CheckBoxDemo.java that creates the check boxes in the previous example and reacts to clicks.
//In initialization code:
    chinButton = new JCheckBox("Chin");
    chinButton.setMnemonic(KeyEvent.VK_C); 
    chinButton.setSelected(true);

    glassesButton = new JCheckBox("Glasses");
    glassesButton.setMnemonic(KeyEvent.VK_G); 
    glassesButton.setSelected(true);

    hairButton = new JCheckBox("Hair");
    hairButton.setMnemonic(KeyEvent.VK_H); 
    hairButton.setSelected(true);

    teethButton = new JCheckBox("Teeth");
    teethButton.setMnemonic(KeyEvent.VK_T); 
    teethButton.setSelected(true);

    //Register a listener for the check boxes.
    chinButton.addItemListener(this);
    glassesButton.addItemListener(this);
    hairButton.addItemListener(this);
    teethButton.addItemListener(this);
...
public void itemStateChanged(ItemEvent e) {
    ...
    Object source = e.getItemSelectable();

    if (source == chinButton) {
        //...make a note of it...
    } else if (source == glassesButton) {
        //...make a note of it...
    } else if (source == hairButton) {
        //...make a note of it...
    } else if (source == teethButton) {
        //...make a note of it...
    }

    if (e.getStateChange() == ItemEvent.DESELECTED)
        //...make a note of it...
    ...
    updatePicture();
}

How to Use Radio Buttons

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected. The Swing release supports radio buttons with the JRadioButton and ButtonGroup classes. To put a radio button in a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-many choices are combo boxes and lists. Radio buttons look similar to check boxes, but, by convention, check boxes place no limits on how many items can be selected at a time.
Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual button characteristics, as discussed earlier in this section. For example, you can specify the image displayed in a radio button.
Here is a picture of an application that uses five radio buttons to let you choose which kind of pet is displayed:
A snapshot of RadioButtonDemo

Try this: 
  1. Click the Launch button to run the RadioButton Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.Launches the ButtonDemo example
  2. Click the Dog button or press Alt-d.
    The Dog button becomes selected, which makes the Bird button become unselected. The picture switches from a bird to a dog. This application has one action listener that listens to all the radio buttons. Each time the action listener receives an event, the application displays the picture for the radio button that was just clicked.

Each time the user clicks a radio button (even if it was already selected), the button fires an action event. One or two item events also occur — one from the button that was just selected, and another from the button that lost the selection (if any). Usually, you handle radio button clicks using an action listener.
Below is the code from RadioButtonDemo.java that creates the radio buttons in the previous example and reacts to clicks.
//In initialization code:
    //Create the radio buttons.
    JRadioButton birdButton = new JRadioButton(birdString);
    birdButton.setMnemonic(KeyEvent.VK_B);
    birdButton.setActionCommand(birdString);
    birdButton.setSelected(true);

    JRadioButton catButton = new JRadioButton(catString);
    catButton.setMnemonic(KeyEvent.VK_C);
    catButton.setActionCommand(catString);

    JRadioButton dogButton = new JRadioButton(dogString);
    dogButton.setMnemonic(KeyEvent.VK_D);
    dogButton.setActionCommand(dogString);

    JRadioButton rabbitButton = new JRadioButton(rabbitString);
    rabbitButton.setMnemonic(KeyEvent.VK_R);
    rabbitButton.setActionCommand(rabbitString);

    JRadioButton pigButton = new JRadioButton(pigString);
    pigButton.setMnemonic(KeyEvent.VK_P);
    pigButton.setActionCommand(pigString);

    //Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(birdButton);
    group.add(catButton);
    group.add(dogButton);
    group.add(rabbitButton);
    group.add(pigButton);

    //Register a listener for the radio buttons.
    birdButton.addActionListener(this);
    catButton.addActionListener(this);
    dogButton.addActionListener(this);
    rabbitButton.addActionListener(this);
    pigButton.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
    picture.setIcon(new ImageIcon("images/" 
                                  + e.getActionCommand() 
                                  + ".gif"));
}
For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup takes care of unselecting the previously selected button when the user selects another button in the group.
You should generally initialize a group of radio buttons so that one is selected. However, the API doesn't enforce this rule — a group of radio buttons can have no initial selection. Once the user has made a selection, exactly one button is selected from then on.

The Button API

The following tables list the commonly used button-related API. Other methods you might call, such as setFont and setForeground, are listed in the API tables in The JComponent Class.
The API for using buttons falls into these categories:

Wednesday, 19 June 2013

19th june 2013

 Containers and Components

AWT_ContainerComponent.png
There are two types of GUI elements:
  1. Component: Components are elementary GUI entities (such as ButtonLabel, and TextField.)
  2. Container: Containers (such as FramePanel and Applet) are used to hold components in a specific layout. A container can also hold sub-containers.
GUI components are also called controls (Microsoft ActiveX Control), widgets (Eclipse's Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with the application via mouse, keyboard, and other forms of inputs such as voice.
In the above example, there are three containers: a Frame and two Panels. A Frame is the top-level container of an AWT GUI program. AFrame has a title bar (containing an icon, a title, and the minimize/maximize(restore-down)/close buttons), an optional menu bar and the content display area. A Panel is a rectangular area (or partition) used to group related GUI components in a certain layout. In the above example, 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).
In a GUI program, a component must be kept in a container. You need to identify a container to hold the components. Every container has a method called add(Component c). A container (says aContainer) can invokeaContainer.add(aComponent) to add aComponent into itself. For example,
Panel panel = new Panel();        // Panel is a Container
Button btn = new Button("Press"); // Button is a Component
panel.add(btn);                   // The Panel Container adds a Button Component

2.3  AWT Container Classes

Top-Level Containers: FrameDialog and Applet
Each GUI program has a top-level container. The commonly-used top-level containers in AWT are FrameDialog and Applet:
  • AWT_Frame.pngFrame 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 from java.awt.Frame to inherit the main window as follows:
    import java.awt.Frame;  // Using Frame class in package java.awt
    
    // A GUI program is written as a subclass of Frame - the top-level container
    // This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane
    public class MyGUIProgram extends Frame {
       // Constructor to setup the GUI components
       public MyGUIProgram() { ...... }
    
       ......
       ......
    
       // The entry main() method
       public static void main(String[] args) {
          // Invoke the constructor (to setup the GUI) by allocating an instance
          MyGUIProgram m = new MyGUIProgram();
       }
    }
  • AWT_Dialog.gifAn 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 (partition) under a higher-level container, used to layout a set of related GUI components. See the above examples for illustration.
  • ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.
  • others.
Hierarchy of the AWT Container Classes
The hierarchy of the AWT Container classes is as follows:
AWT_ContainerClassDiagram.png

2.4  AWT Component Classes

AWT provides many ready-made and reusable GUI components. The frequently-used are: ButtonTextFieldLabelCheckboxCheckboxGroup (radio buttons), List, and Choice, as illustrated below.
AWT_Components.png
AWT GUI Component: Label
AWT_Label.png
java.awt.Label provides a text description message. 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.
Check the JDK API specification for java.awt.Label.
Constructors
public Label(String strLabel, int alignment); // Construct a Label with the given text String, of the text alignment
public Label(String strLabel);                // Construct a Label with the given text String
public Label();                               // Construct an initially empty Label
The Label class has three constructors:
  1. The first constructor constructs a Label object with the given text string in the given alignment. Note that three static constants Label.LEFTLabel.RIGHT, and Label.CENTER are defined in the class for you to specify the alignment (rather than asking you to memorize arbitrary integer values).
  2. The second constructor constructs a Label object with the given text string in default of left-aligned.
  3. The third constructor constructs a Label object with an initially empty string. You could set the label text via the setText() method later.
Constants
public static final LEFT;    // Label.LEFT
public static final RIGHT;   // Label.RIGHT
public static final CENTER;  // Label.CENTER
These three constants are defined for specifying the alignment of the Label's text.
Public Methods
// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment);
The getText() and setText() methods can be used to read and modify the Label's text. Similarly, the getAlignment() and setAlignment() methods can be used to retrieve and modify the alignment of the text.
Constructing a Component and Adding the Component into a Container
Three steps are necessary to create and place a GUI component:
  1. Declare the component with an identifier;
  2. Construct the component by invoking an appropriate constructor via the new operator;
  3. Identify the container (such as Frame or Panel) designed to hold this component. The container can then add this component onto itself via aContainer.add(aComponent) method. Every container has a add(Component) method. Take note that it is the container that actively and explicitly adds a component onto itself, instead of the other way.


AWT GUI Component: Button
AWT_Button.png
java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.
Constructors
public Button(String buttonLabel);
   // Construct a Button with the given label
public Button();
   // Construct a Button with empty label

The Button class has two constructors. The first constructor creates a Button object with the given label painted over the button. The second constructor creates a Button object with no label.
AWT GUI Component: TextField
AWT_TextField.png
java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-line text box called TextArea.) Hitting the "ENTER" key on a TextField object triggers an action-event.
Constructors
public TextField(String strInitialText, int columns);
   // Construct a TextField instance with the given initial text string with the number of columns.
public TextField(String strInitialText);
   // Construct a TextField instance with the given initial text string.
public TextField(int columns);
   // Construct a TextField instance with the number of columns.

Tuesday, 18 June 2013

11th day of training

 Introduction to GUI 

So far, we have covered most of the basic constructs of Java and introduced the important concept of Object-Oriented Programming (OOP). As discussed, OOP permits higher level of abstraction than the traditional procedural-oriented languages (such as C and Pascal). OOP lets you think in the problem space rather than the computer's bits and bytes. You can create high-level abstract data types calledclasses to mimic real-life things and represent entities in the problem space. These classes are self-contained and are reusable.
In this article, I shall show you how you can reuse the graphics classes provided in JDK for constructing your own Graphical User Interface (GUI) applications. Writing your own graphics classes (re-inventing the wheels) will take you many years! These graphics classes, developed by expert programmers, are highly complex and involve many advanced Java concepts.  However, re-using them are not so difficult, if you follow the API documentation, samples and templates provided.
I shall also describe an important concept called nested class (or inner class) in this article.
There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and Swing.
  1. AWT API was introduced in JDK 1.0. Most of the AWT components have become obsolete and should be replaced by newer Swing components.
  2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC, which consists of Swing, Java2D, Accessibility API, Internationalization, and Pluggable Look-and-Feel Support, was an add-on to JDK 1.1 but has been integrated into core Java since JDK 1.2.
Other than AWT/Swing Graphics APIs provided in JDK, others have also provided Graphics APIs that work with Java, such as Eclipse's Standard Widget Toolkit (SWT), Google Web Toolkit (GWT), 3D Graphics API such as Java bindings for OpenGL (JOGL) and Java3D.

Programming GUI with AWT

Java Graphics APIs - AWT and Swing - provide a huge set of reusable GUI components, such as button, text field, label, choice, panel and frame for building GUI applications. You can simply reuse these classes rather than re-invent the wheels. I shall start with the AWT classes before moving into Swing to give you a complete picture. I have to stress that many AWT component classes are now obsolete. They are used only in exceptional circumstances when the JRE supports only JDK 1.1.

2.1  AWT Packages

AWT is huge! It consists of 12 packages (Swing is even bigger, with 18 packages as of JDK 1.7!). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.
  1. The java.awt package contains the core AWT graphics classes:
    • GUI Component classes (such as ButtonTextField, and Label),
    • GUI Container classes (such as FramePanelDialog and ScrollPane),
    • Layout managers (such as FlowLayoutBorderLayout and GridLayout),
    • Custom graphics classes (such as GraphicsColor and Font).
  2. The java.awt.event package supports event handling:
    • Event classes (such as ActionEventMouseEventKeyEvent and WindowEvent),
    • Event Listener Interfaces (such as ActionListenerMouseListenerKeyListener and WindowListener),
    • Event Listener Adapter classes (such as MouseAdapterKeyAdapter, and WindowAdapter).
AWT provides a platform-independent and device-independent interface to develop graphic programs that runs on all platforms, such as Windows, Mac, and Linux.

Friday, 14 June 2013

10th day of training

Using the Keyword super

Accessing Superclass Members

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}
Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from SuperclassSubclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
Printed in Superclass.
Printed in Subclass

Subclass Constructors

The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike(subclass) constructor that calls the superclass constructor and then adds initialization code of its own:
public MountainBike(int startHeight, 
                    int startCadence,
                    int startSpeed,
                    int startGear) {
    super(startCadence, startSpeed, startGear);
    seatHeight = startHeight;
}   
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();  
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.