SWING - Radio Buttons

java.lang.Object
extended byjava.awt.Component
extended byjava.awt.Container
extended byjavax.swing.JComponent
extended byjavax.swing.AbstractButton
extended byjavax.swing.JToggleButton
extended byjavax.swing.JRadioButton

Constructor Summary
JRadioButton()
Creates an initially unselected radio button with no set text.
JRadioButton(Action a)
Creates a radiobutton where properties are taken from the Action supplied.
JRadioButton(Icon icon)
Creates an initially unselected radio button with the specified image but no text.
JRadioButton(Icon icon, boolean selected)
Creates a radio button with the specified image and selection state, but no text.
JRadioButton(String text)
Creates an unselected radio button with the specified text.
JRadioButton(String text, boolean selected)
Creates a radio button with the specified text and selection state.
JRadioButton(String text, Icon icon)
Creates a radio button that has the specified text and image, and that is initially unselected.
JRadioButton(String text, Icon icon, boolean selected)
Creates a radio button that has the specified text, image, and selection state.

Method Summary
protected void configurePropertiesFromAction(Action a)
Factory method which sets the ActionEvent source's properties according to values from the Action instance.
protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Factory method which creates the PropertyChangeListener used to update the ActionEvent source as properties change on its Action instance.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JRadioButton.
String getUIClassID()
Returns the name of the L&F class that renders this component.
protected String paramString()
Returns a string representation of this JRadioButton.
void updateUI()
Resets the UI property to a value from the current look and feel.

Example

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Radiobutton extends JApplet implements ItemListener{
JTextField text;
JRadioButton radio1, radio2, radio3, radio4;
ButtonGroup group;

public void init() {

Container frame1=getContentPane();
frame1.setLayout(new FlowLayout());

group=new ButtonGroup();

radio1=new JRadioButton("Radio Button 1");
radio2=new JRadioButton("Radio Button 2");
radio3=new JRadioButton("Radio Button 3");
radio4=new JRadioButton("Radio Button 4");
text=new JTextField(20);

group.add(radio1);
group.add(radio2);
group.add(radio3);
group.add(radio4);

radio1.addItemListener(this);
radio2.addItemListener(this);
radio3.addItemListener(this);
radio4.addItemListener(this);

frame1.add(radio1);
frame1.add(radio2);
frame1.add(radio3);
frame1.add(radio4);

frame1.add(text);
}

public void itemStateChanged(ItemEvent e){
if(e.getItemSelectable()==radio1){
text.setText("You Select Radio Button 1");
}else if(e.getItemSelectable()==radio2){
text.setText("You Select Radio Button 2");
}else if(e.getItemSelectable()==radio3){
text.setText("You Select Radio Button 3");
}else if(e.getItemSelectable()==radio4){
text.setText("You Select Radio Button 4");
}


}
}

Output

SWING - Check Boxes

java.lang.Object
extended byjava.awt.Component
extended byjava.awt.Container
extended byjavax.swing.JComponent
extended byjavax.swing.AbstractButton
extended byjavax.swing.JToggleButton
extended byjavax.swing.JCheckBox

Constructor Summary
JCheckBox()
Creates an initially unselected check box button with no text, no icon.
JCheckBox(Action a)
Creates a check box where properties are taken from the Action supplied.
JCheckBox(Icon icon)
Creates an initially unselected check box with an icon.
JCheckBox(Icon icon, boolean selected)
Creates a check box with an icon and specifies whether or not it is initially selected.
JCheckBox(String text)
Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected)
Creates a check box with text and specifies whether or not it is initially selected.
JCheckBox(String text, Icon icon)
Creates an initially unselected check box with the specified text and icon.
JCheckBox(String text, Icon icon, boolean selected)
Creates a check box with text and icon, and specifies whether or not it is initially selected.

Method Summary
protected void configurePropertiesFromAction(Action a)
Factory method which sets the ActionEvent source's properties according to values from the Action instance.
protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Factory method which creates the PropertyChangeListener used to update the ActionEvent source as properties change on its Action instance.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBox.
String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
boolean isBorderPaintedFlat()
Gets the value of the borderPaintedFlat property.
protected String paramString()
Returns a string representation of this JCheckBox.
void setBorderPaintedFlat(boolean b)
Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the appearance of the check box border.
void updateUI()
Resets the UI property to a value from the current look and feel.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class checkbox extends JApplet implements ItemListener{
JTextField text;
JCheckBox checkbox1, checkbox2, checkbox3, checkbox4;

public void init() {

Container frame1=getContentPane();
frame1.setLayout(new FlowLayout());


checkbox1=new JCheckBox("Check Box1");
checkbox2=new JCheckBox("Check Box2");
checkbox3=new JCheckBox("Check Boz3");
checkbox4=new JCheckBox("Check Box4");
text=new JTextField(20);

checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
checkbox3.addItemListener(this);
checkbox4.addItemListener(this);

frame1.add(checkbox1);
frame1.add(checkbox2);
frame1.add(checkbox3);
frame1.add(checkbox4);

frame1.add(text);
}

public void itemStateChanged(ItemEvent e){
if(e.getItemSelectable()==checkbox1){
text.setText("Hello from Swing");
}else if(e.getItemSelectable()==checkbox2){
text.setText("Hello from Swing");
}else if(e.getItemSelectable()==checkbox3){
text.setText("Hello from Swing");
}else if(e.getItemSelectable()==checkbox4){
text.setText("Hello from Swing");
}


}
}

SWING - JButton

java.lang.Object
extended byjava.awt.Component
extended byjava.awt.Container
extended byjavax.swing.JComponent
extended byjavax.swing.AbstractButton
extended byjavax.swing.JButton

Swaing button let you do a lot more than AWT buttons. Some of the things you can do with the JButton class include using setToolTipText to add a tooltip to the button, using setMargin to set the inserts in the button itself, using doClick to click the button from code, adding images to the button, and adding mnemonics (Keyboard shortcuts) to the button. Of course, you can do standard AWT things with JButton too, such as using setEnabled to enable or disable the button, using addActionListener to register an action listener with the button and adding action commands to JButton objects with setActionCommand.

Constructor Summary
JButton()
Creates a b0utton with no set text or icon.
JButton(Action a)
Creates a button where properties are taken from the Action supplied.
JButton(Icon icon)
Creates a button with an icon.
JButton(String text)
Creates a button with text.
JButton(String text, Icon icon)
Creates a button with initial text and an icon.

Method Summary
protected void configurePropertiesFromAction(Action a)
Factory method which sets the AbstractButton's properties according to values from the Action instance.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JButton.
String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
boolean isDefaultButton()
Gets the value of the defaultButton property, which if true means that this button is the current default button for its JRootPane.
boolean isDefaultCapable()
Gets the value of the defaultCapable property.
protected String paramString()
Returns a string representation of this JButton.
void removeNotify()
Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane, and if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.
void setDefaultCapable(boolean defaultCapable)
Sets the defaultCapable property, which determines whether this button can be made the default button for its root pane.
void updateUI()
Resets the UI property to a value from the current look and feel.

Example:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class jbutton extends JApplet{
JTextField text=new JTextField(20);
JButton button=new JButton("Click Here");
public void init() {
Container frame1=getContentPane();
frame1.setLayout(new FlowLayout());
frame1.add(text);
frame1.add(button);

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
text.setText("Hello from Swing");
}
});
}
}

Output:

Displaying Images in Button

It is easy to display images in buttons using the ImageIcon class, because several JButton constructors let you add icons to buttons. You can also set the alignment of the text and image using these AbstractButton methods.

setVerticalTextAlignment - Sets the vertical text alignment relative to the image.

setHorizontalAlignment - Sets the horizontal text alignment relative to the image.

setVerticalAlignment - Sets the vertical alignment of the button's contents.

setHorizontalAlignment - Sets the horizontal alignment of the button's contents.

Lets' look at an example in which i add an image from button.jpg to the button example from the previous,

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class jbutton extends JApplet{
JTextField text=new JTextField(20);
JButton button=new JButton("asass", new ImageIcon("button1.jpg"));
public void init() {
Container frame1=getContentPane();
frame1.setLayout(new FlowLayout());
frame1.add(text);
frame1.add(button);

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
text.setText("Hello from Swing");
}
});
}

}

Default Buttons and Mnemonics

Besides making buttons into default buttons, you can also give each button a mnemonic, which is a keyboard shortcut, much like those you see in menus. You underline one (case-insensitive) letter in a button's caption, and when the button has the focus, typing that character activates the button.

Example:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class jbutton extends JApplet{
JTextField text=new JTextField(20);
JButton button1=new JButton("Click Here");
JButton button2=new JButton("Click Here 1");
public void init() {
Container frame1=getContentPane();
frame1.setLayout(new FlowLayout());

button2.setMnemonic('l');
getRootPane().setDefaultButton(button2);


frame1.add(text);
frame1.add(button1);
frame1.add(button2);
getRootPane().requestFocus();

button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
text.setText("Hello from Swing");
}
});
}
}

Output:

SWING - JTextBox

java.lang.Object
extended byjava.awt.Component
extended byjava.awt.Container
extended byjavax.swing.JComponent
extended byjavax.swing.text.JTextComponent
extended byjavax.swing.JTextField
Constructor Summary
JTextField()
Constructs a new TextField.
JTextField(Document doc, String text, int columns)
Constructs a new JTextField that uses the given text storage model and the given number of columns.
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
JTextField(String text)
Constructs a new TextField initialized with the specified text.
JTextField(String text, int columns)
Constructs a new TextField initialized with the specified text and columns.

Method Summary
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.
protected void configurePropertiesFromAction(Action a)
Factory method which sets the ActionEvent source's properties according to values from the Action instance.
protected PropertyChangeListener createActionPropertyChangeListener(Action a)
Factory method which creates the PropertyChangeListener used to update the ActionEvent source as properties change on its Action instance.
protected Document createDefaultModel()
Creates the default implementation of the model to be used at construction if one isn't explicitly given.
protected void fireActionPerformed()
Notifies all listeners that have registered interest for notification on this event type.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JTextField.
Action getAction()
Returns the currently set Action for this ActionEvent source, or null if no Action is set.
ActionListener[] getActionListeners()
Returns an array of all the ActionListeners added to this JTextField with addActionListener().
Action[] getActions()
Fetches the command list for the editor.
int getColumns()
Returns the number of columns in this TextField.
protected int getColumnWidth()
Returns the column width.
int getHorizontalAlignment()
Returns the horizontal alignment of the text.
BoundedRangeModel getHorizontalVisibility()
Gets the visibility of the text field.
Dimension getPreferredSize()
Returns the preferred size Dimensions needed for this TextField.
int getScrollOffset()
Gets the scroll offset, in pixels.
String getUIClassID()
Gets the class ID for a UI.
boolean isValidateRoot()
Calls to revalidate that come from within the textfield itself will be handled by validating the textfield, unless the textfield is contained within a JViewport, in which case this returns false.
protected String paramString()
Returns a string representation of this JTextField.
void postActionEvent()
Processes action events occurring on this textfield by dispatching them to any registered ActionListener objects.
void removeActionListener(ActionListener l)
Removes the specified action listener so that it no longer receives action events from this textfield.
void scrollRectToVisible(Rectangle r)
Scrolls the field left or right.
void setAction(Action a)
Sets the Action for the ActionEvent source.
void setActionCommand(String command)
Sets the command string used for action events.
void setColumns(int columns)
Sets the number of columns in this TextField, and then invalidate the layout.
void setDocument(Document doc)
Associates the editor with a text document.
void setFont(Font f)
Sets the current font.
void setHorizontalAlignment(int alignment)
Sets the horizontal alignment of the text.
void setScrollOffset(int scrollOffset)
Sets the scroll offset, in pixels.

Example:

import java.awt.*;
import javax.swing.*;

public class jtextbox extends JApplet{
JTextField text= new JTextField(18);

public jtextbox() {
Container frame = getContentPane();
frame.setLayout(new FlowLayout());
frame.add(text);
text.setText("Hellow From Java");
}
}

SWING - Label

java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JLabel
Constructor Summary
JLabel()
Creates a JLabel instance with no image and with an empty string for the title.
JLabel(Icon image)
Creates a JLabel instance with the specified image.
JLabel(Icon image, int horizontalAlignment)
Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(String text)
Creates a JLabel instance with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)
Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment.

Method Summary
protected int checkHorizontalKey(int key, String message)
Verify that key is a legal value for the horizontalAlignment properties.
protected int checkVerticalKey(int key, String message)
Verify that key is a legal value for the verticalAlignment or verticalTextPosition properties.
AccessibleContext getAccessibleContext()
Get the AccessibleContext of this object
Icon getDisabledIcon()
Returns the value of the disabledIcon property if it's been set, If it hasn't been set and the value of the icon property is an ImageIcon, we compute a "grayed out" version of the icon and update the disabledIcon property with that.
int getDisplayedMnemonic()
Return the keycode that indicates a mnemonic key.
int getDisplayedMnemonicIndex()
Returns the character, as an index, that the look and feel should provide decoration for as representing the mnemonic character.
int getHorizontalAlignment()
Returns the alignment of the label's contents along the X axis.
int getHorizontalTextPosition()
Returns the horizontal position of the label's text, relative to its image.
Icon getIcon()
Returns the graphic image (glyph, icon) that the label displays.
int getIconTextGap()
Returns the amount of space between the text and the icon displayed in this label.
Component getLabelFor()
Get the component this is labelling.
String getText()
Returns the text string that the label displays.
LabelUI getUI()
Returns the L&F object that renders this component.
String getUIClassID()
Returns a string that specifies the name of the l&f class that renders this component.
int getVerticalAlignment()
Returns the alignment of the label's contents along the Y axis.
int getVerticalTextPosition()
Returns the vertical position of the label's text, relative to its image.
boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h)
This is overridden to return false if the current Icon's Image is not equal to the passed in Image img.
protected String paramString()
Returns a string representation of this JLabel.
void setDisabledIcon(Icon disabledIcon)
Set the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)).
void setDisplayedMnemonic(char aChar)
Specifies the displayedMnemonic as a char value.
void setDisplayedMnemonic(int key)
Specify a keycode that indicates a mnemonic key.
void setDisplayedMnemonicIndex(int index)
Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.
void setHorizontalAlignment(int alignment)
Sets the alignment of the label's contents along the X axis.
void setHorizontalTextPosition(int textPosition)
Sets the horizontal position of the label's text, relative to its image.
void setIcon(Icon icon)
Defines the icon this component will display.
void setIconTextGap(int iconTextGap)
If both the icon and text properties are set, this property defines the space between them.
void setLabelFor(Component c)
Set the component this is labelling.
void setText(String text)
Defines the single line of text this component will display.
void setUI(LabelUI ui)
Sets the L&F object that renders this component.
void setVerticalAlignment(int alignment)
Sets the alignment of the label's contents along the Y axis.
void setVerticalTextPosition(int textPosition)
Sets the vertical position of the label's text, relative to its image.
void updateUI()
Resets the UI property to a value from the current look and feel.

Example:

import java.awt.*;
import javax.swing.*;

public class jlabel extends JApplet{
public jlabel() {
Container contentpane=getContentPane();
JLabel label=new JLabel("Hello from Java");
contentpane.setLayout(new FlowLayout()); //Used for Line Alignment
contentpane.add(label);
}
}

The ImageIcon class lets you create an icon from an image file for use in a Swing control.

Constructor Summary
ImageIcon()
Creates an uninitialized image icon.
ImageIcon(byte[] imageData)
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF or JPEG.
ImageIcon(byte[] imageData, String description)
Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF or JPEG.
ImageIcon(Image image)
Creates an ImageIcon from an image object.
ImageIcon(Image image, String description)
Creates an ImageIcon from the image.
ImageIcon(String filename)
Creates an ImageIcon from the specified file.
ImageIcon(String filename, String description)
Creates an ImageIcon from the specified file.
ImageIcon(URL location)
Creates an ImageIcon from the specified URL.
ImageIcon(URL location, String description)
Creates an ImageIcon from the specified URL.

Method Summary
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this ImageIcon.
String getDescription()
Gets the description of the image.
int getIconHeight()
Gets the height of the icon.
int getIconWidth()
Gets the width of the icon.
Image getImage()
Returns this icon's Image.
int getImageLoadStatus()
Returns the status of the image loading operation.
ImageObserver getImageObserver()
Returns the image observer for the image.
protected void loadImage(Image image)
Loads the image, returning only when the image is loaded.
void paintIcon(Component c, Graphics g, int x, int y)
Paints the icon.
void setDescription(String description)
Sets the description of the image.
void setImage(Image image)
Sets the image displayed by this icon.
void setImageObserver(ImageObserver observer)
Sets the image observer for the image.
String toString()
Returns a string representation of this image.

Example:

import java.awt.*;
import javax.swing.*;

public class jlabel extends JApplet{

public void jlabel() {
Container contentPane=getContentPane();


JLabel label=new JLabel("Label", new ImageIcon("label.jpg"), JLabel.CENTER);
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);


contentPane.add(label);
}



SWING - Applets, Applications and Pluggable Look And Feel

Swing is a set of packages built on top of the AWT that provides you with a great number of prebuilt classes (over 250 classes and 40UI components). These 40 UI Components are:

  • JApplet - An extended version of java.applet.Applet that adds support for root panes and other panes
  • JButton - A push and command button
  • JCheckBox - A check box that can be selected or deselected, displaying its state visually.
  • JCheckBoxMenuItem - A menu item that can be selected or deselected, displaying its state visually.
  • JColorChooser - A pane of controls to allow a user to select a color.
  • JComboBox - A combo box, which is a combination of a test field and dropdown list.
  • JComponent - The base class for swing components
  • JDesktopPane - A container used to create a multiple-document interface or a desktop.
  • JDialog - The base class for creating a dialog window.
  • JEditorPane - A text component that allows the user o edit various kinds of content.
  • JFileChooser - Lets the user choose a file.

  • JFrame - An extended version of java.awt.Frane that adds support root panes and other panes.

  • JInternalFrame - A lightweight object that provides many of the features of a heavyweight frame.

  • JInternalFrame.JDesktopIcon - Represents an inconified version of a JInternalFrame.

  • JLabel - A display area for a short text string or an image or both.

  • JLayeredPane - Adds layers to a Swing container, allowing components to overlap each other.

  • JList - A components that allows the user to select one or more objects from list.

  • JMenu - A pop-up menu containing JMenuItems that's displayed when the user selects it in the JMenuBar component.

  • JMenuBar - An implementation of menu bar.

  • JMenuItem - An implementation of menu item.

  • JObjectPane - Makes it easy to pop up a standard dialog box.

  • JPanel - A generic lightweight container.

  • JPasswordField - Allows editing of a single line of text where the view does not show the original characters.

  • JPopupMenu - A pop-up menu.

  • JPopupMenu.Separator - A pop-up menu specific separator

  • JProgressBar - A component that displays an integer value within an interval.

  • JRadioButton - A radio button that can be selected or deselected, displaying its state visually

  • JRadioButtonMenuItem - An radio button menu item.

  • JRootPane - The fundamental component in the container hierarchy.

  • JScrollBar - An implementation of a scrollbar.

  • JScrollPane - A container that manages a view port, optional vertical and horizontal scrollbars and optional row and column heading view ports.

  • JSeparator - A menu separator.

  • JSlider - A component that lets the user select a value by sliding a knob within an interval.

  • JSplitPane - Divides two components.

  • JTabbedPane - Lets the user switch between a group of components by clicking tabs.

  • JTable - Presents data in a two dimensional table format

  • JTextArea - A multiline area that displays text.

  • JTextField - Allows the editing of a single line of text.

  • JTextPane - A text component that can be marked up with attributes.

  • JToggleButton - A two-state button

  • JToggleButton.ToggleButtonModel - The toggle button model

  • JToolBar - A toolbar, useful for displaying commonly used controls.

  • JToolBar.Separator - A toolbar-separator

  • JToolTip - Displays a tool tip for a component

  • JTree - Displays a set of hierarchical data as an outline

  • JTree.DynamicUtilTreeNode - Can wrap vectors/ hashtables/ arrays/ strings and create appropriate children tree nodes

  • JTree.EmptySelectionModel - A trees election model that does not allow anything to be selected.

  • JViewport - The view port through which you see the information

  • JWindow - A window that can be displayed anywhere on the desktop

Inheritance, Inner Classes and Interfaces

Inheritance

Example, an applet create a super class based on the Applet class using the extends keyword-

import java.applet.Applet; //File Name is applet.java
import java.awt.*;
public class applet extends Applet //Here applet is a user defined class and Applet is library class of java
{
public void paint(Graphics g) // Here Graphics is a library class of super class Applet
{
g.drawString("Hello from Java",60,100); //Here drawString is a library method of class Applet
}
}

Interface

Suppose you want to create an applet that handles button clicks. To create a standard applet, you can derive a class from the java.applet.Applet class, and to handle button clicks, you use another class, ActionListener. Therefore, it looks as through you'll have to base your applet on the Applet and ActionListener classes.

In this case, that means you can extend your applet from the Applet class and use the implements keyword to add the button-click handling.

Example:

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

public class clicker extends Applet implements ActionListener{
TextField text1;
Button button1;

public void init(){
text1=new TextField(20);
add(text1);
button1=new Button("Click Here");
add(button1);
button1.addActionListener(this);
}

public void actionPerformed(ActionEvent event){
String msg=new String("Welcome to Java");
if(event.getSource()==button1){
text1.setText(msg);
}
}
}

Inner Class

Java now lets you creates within classes, and the enclosed class is called an inner class. You might not see much need for defining classes within classes now, but it will become more apparent when we start handling user interface events, such as when the user closes a window.

Events are handled with interfaces and when you implement an interface, you must also provide implementations of several abstract methods inside the interface. To make this process easier, java provides adapter classes (Inner Class)

Example:

AppFrame.java file contains-

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

public class AppFrame extends Frame
{
public void paint(Graphics g)
{
g.drawString("Hello from Java..",60,100);
}
}

App.java file contains-

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

public class App
{
public static void main(String[] args)
{
AppFrame f=(new AppFrame());
f.setSize(200,200);
f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});
f.show();
}
}

Object-Oriented Programming

In Java, object-oriented programming involves around a few key concepts: classes, objects, data members, methods, and inheritance.

Class: A class is a template from which you can create objects. The definition of the class includes the formal specifications for the class and any data and methods in it. Example:

Object: An object is an instance of a class, much as a variable is an instance of a data type. You can think of a class as the type of an object and you can think of the object as an instance of a class. Objects encapsulate methods and variables. Example:

Data member: it is those variable that are part of a class, and they're how you store the data the object uses.

Method: it is a function built into a class or object. Example:

Inheritance: It is the of driving one class, called the drive class, from another, called the base class, and bring able to make use of the base class's methods in the derive class.

Example: There are two Java files one is cal.java and another is appClass.java

cal.java file contains -

public class cal //Here cal is a Class
{
public int c=2; // Here c is a Variable or Data Member declared in class cal
public int calculate(int a, int b){ // Here calculate is a Method declared in class cal
return a+b;
}
}

appClass file contains -

public class appClass //Here appClass is the main class because it contains main(String[] args
{
public static void main(String[] args)
{
int y;
cal cal1= new cal(); //Here cal1 is a Object of class cal
y=cal1.calculate(7,cal1.c); //Here cal1 takes the functionality of the method (calculate) and value of the variable (c) of class cal
System.out.println(y);
}
}

Output -

9

Some other important concepts are,

Command-line Arguments Passed to Main:

Constructors:

Overloading Methods:

Overloading Constructors:

Passing Objects to Methods:

Declaring and Defining Class:

Syntax:

[access] class classname [extends ...] [implements ...]
{
// class definition goes here.
}

Ex. We'll make just create a very simple class named printer that defines one method, print. When i call the print method, it displays the message "Hello from Java!" on the console.

class printer
{
public void print()
{
System.out.println("Hello from Java!");
}
}
public class app
{
public static void main( String[] args)
{
printer printer1 = new printer();
printer1.print();
}
}

=> Take a moment to study this example; note that I'm declaring and defining two classes, printer and app, in the same file here. Only one class can be public in one file, and that's app in this case. The file, itself, must be named after that class, which here means the containing file must be app.java.

Ex. We can also divide this example into two files, one for each class. Here's printer.java:

class printer
{
public void print()
{
System.out.println("Hello from Java!");
}
}

And here's app.java:

import printer;
public class app
{
public static void main( String[] args)
{
printer printer1 = new printer();
printer1.print();
}
}

Creating Instance Variables:

we can store data in classes in two ways - as instance variables or as class variables.

Syntax:

[access] class classname [extends ...] [implements ...]
{
[access] type instance_variable1;
... ... ... ...
... ... ... ...
[access] type instance_variableN;
}

Ex. We'll create a class named Date that holds a String instance variable named data_string, which in turn holds the text "Hello from Java!":

class Data
{
public String data_string = "Hello from Java!";
}
public class app
{
public static void main( String[] args)
{
Data data=new Data();
String string=data.data_string;
System.out.println(string);
}
}

Setting Variable Access:

You can use an access specifier - called access in the following code - to set the visibility of a class's data members as far as the rest of the program is concerned.

Syntax:

[access] class classname [extends ...] [implements ...]
{
[access] type instance_variable1;
... ... ... ...
... ... ... ...
[access] type instance_variableN;
}

=> The possible value for access are public, private and protected. When you declare a class member public, it's accessible from anywhere in your program. If you declare it private, it's accessible only in the class it's member of. If you declare it protected, it's available to the current class, other classes in the same package. If you don't use an access specifier, the default access is that the class member is visible to the class it's a member of, to classes derived from that class in the same package, and to other classes in the same package.

Ex. if we wanted to make the instance variable data_string private to the Data class created in the previous topic, we can declare it private,

class Date
{
private String data_string = "Hello from Java!";
}
public class app
{
public static void main( String[] args)
{
Data data=new Data();
String string=data.data_string;
System.out.println(string);
}
}

=> Now, if we try to access the data_string instance variable in another class, as i do previously in the app class, the Java compiler will object:

Output:

app.java:10: data_string has private access in Data
String string=data.data_string;
^
1 error

Table: Scope by specifier (x=in scope).

Location Private No Modifier Protected Public
Same class X X X X
Subclass in the same package X X X
Non subclass in the same package X X X
Subclass in another package X X
Non-subclass in another package X

Creating Class Variable:

The value in a class variable is shared by all objects of that class, which means it will be the same for all objects. You declare a variable as static keyword.

Syntax:

[access] class classname [extends ...] [implements ...]
{
[access] static type instance_variable1;
... ... ... ...
... ... ... ...
[access] static type instance_variableN;
}

Ex. We create a class named data with a class data variable named intdata.

class data
{
public static int intdata=0;
}
public class app
{
public static void main( String[] args)
{
data a, b;
a = new data();
b = new data();
a.intdata = 1;
System.out.println("The Value of b.intdata = "+ b.intdata);
}
}

Output:

The Value of b.intdata = 1b

If you need to perform some calculation to initialize static variables, you can do so in a static code block, which you label with the static keyword; that code is executed joust once, when the class is first loaded.

Ex.

class data
{
public static int intdata =1;
public static int doubleintdata;

static
{
doubleintdata = 2 * intdata;
}
}

public class app
{
public static void main( String[] args)
{
data a;
a = new data();
System.out.println("The value of a.doubleintdate = "+ a.doubleintdata);
}
}

Output:

The value of a.doubleintdate = 2

Creating Methods:

We've been using methods even since printing out our first message with System.out.println, so we're certainly familiar with the concept. A method is a code block that you can transfer control to and so execute that code.

Ex.

class printer
{
public void print()
{
System.out.println("Hello from Java!");
}
}
public class app
{
public static void main( String[] args)
{
printer printer1 = new printer();
printer1.print();
}
}

Setting Method Access:

Ex. we add a private method to the printer class developed over the last few topics. This method may only be called from other methods in the printer class.

class printer
{
public void print()
{
internal_use_only();
}
private void internal_use_only()
{
System.out.println("Hello from Java!");
}
}

public class app
{
public static void main(String[] args)
{
printer printer1 = new printer();
printer1.print();
}
}

Output:

Hello from Java!

=> When you call the printer class's print method, it makes use of the internal_use_only method, which is inaccessible outside the object, to do the actual printing.

Passing Parameters to Methods:

When you declare a method, you can specify a comma-separated list of parameters that you want to pass to that method in the parentheses following the method's name.

Syntax:

[access] [static] type method1 ([type parameter_name1 [, type parameter_name1 . . .]])
{

}

The values passed to the method will then be accessible in the body of the method, using the named we've given them in the parameter list.

Ex. We pass the string to print to the print method. We declare the method like this so that Java knows it will accept one parameter - a String object named s:

class printer
{
public void print( String s)
{
System.out.println(s);
}
}

public class app
{
public static void main(String[] args)
{
(new printer()).print("Hello from Java!");
}
}

Output:

Hello from Java!

Note: If you have more than one parameter to pass, you can specify multiple parameters in the parameter list, separated by commas.

Command-line Arguments passed to Main:

A special array is passed as a parameter to the main method in applications - an array of String objects that holds the command-line arguments the user specified when starting Java.

C:\> java app Now is the time

=> In this case, the first element of the array passed to main will hold "Now", the second "is", the third "the" and the fourth "time".

Ex. This application will print out all the command-line arguments passed to it by looping over the String array passed as a parameter to the main method.

public class app
{
public static void main(String[] args)
{
System.out.println("Command line arguments ...");
for( int index=0 ; index < args.length ; index++ ) {
System.out.println("Argument "+ index +" = "+ args[index]);
}
}
}

Output:

C:\jdk1.3\myproject>java app Hello from Java !

Command line arguments ...
Argument 0 = Hello
Argument 1 = from
Argument 2 = Java
Argument 3 = !

Return Values from Methods:

We can use the return statement in a method to return a value from the method and we indicate what the return type of the method is when we declare the method.

[access] [static] type method1 ([type parameter_name1 [, type parameter_name1 ...]])
{
.........
.........
}

Ex. The class calculator has a method named addem that takes two integers parameters, adds them, and returns the result.

class calculator
{
int addem(int opt1, int opt2)
{
return opt1 + opt2;
}
}

public class app
{
public static void main( String[] args)
{
calculator calc = new calculator();
System.out.println("Addem(2,2) = "+ calc.addem(2,2));
}
}

Output:

Addem(2,2) = 4

Creating Class Method:

To make a method into a class method, use the static keyword.

Ex. We can call the addem method directly using the class name, without creating an object at all.

class calculator
{
static int addem(int opt1, int opt2)
{
return opt1 + opt2;
}
}

public class app
{
public static void main( String[] args)
{
System.out.println("Addem(2,2) = "+ calculator.addem(2,2));
}
}

Output:

Addem(2,2) = 4

Creating Data Access Method:

You can restrict access to the data in your objects using data access methods, which must be called to fetch the data.

Ex. We can provide access to this private data member with two methods: getdata and setdata. The getdata method just returns the value in the private variable data_string.

class data
{
private String data_string="Hello from Java!";

public String getdata()
{
return
data_string;
}

public void setdata( String s)
{
if(
s.length() < 100) {
data_string = s;
}
}
}

public class app
{
public static void main( String[] args)
{
System.out.println((new data()).getdata());
}
}

Output:

Hello from Java!

Creating Constructors:

Creating a constructor for a class is easy; we just add a method to a class with the same name as the class, without any access specifier or return type.

Ex.

class data
{
private String data_string;

data()
{
data_string="Hello from Java!";
}

public String getdata()
{
return data_string;
}
}

public class app
{
public static void main( String[] args)
{
System.out.println((new data()).getdata());
}
}

Output:

Hello from Java!

Passing Parameters to Constructors:

We can pass data to constructors just as we can to other methods.

Ex.

class data
{
private String data_string;

data( String s)
{
data_string=s;
}

public String getdata()
{
return data_string;
}
}

public class app
{
public static void main( String[] args)
{
System.out.println((new data("Hello from Java!")).getdata());
}
}

Output:

Hello from Java!

Using Recursion:

Each time we calla method in java, java allocates new space on its internal stack for all the variables in the method, which means there's no reason you can't call the same method again- a new set of variables will be allocated on the stack automatically. What's more, a method can call itself in java - this is a technique called recursion.

Ex. To calculate the factorial the factorial of positive integer n, called "n!", you calculate the following:

n! = n * (n-1) * (n-2) . . . * 2 * 1

This process lends itself to recursion easily, because each stage of the recursion can calculate one multiplication in which it multiples the number it has been passed by the factorial of the number minus 1. When the number has finally been reduced to 1 through successive calls, the method simply returns and control comes back through the successive stages, performing one multiplication at each stage until all nested calls have returned and you have the factorial.

class calculator
{
public int factorial( int n )
{
if(n==1) {
return n;
}
else {
return n*factorial(n-1);
}
}
}

public class app
{
public static void main( String[] args )
{
calculator calc = new calculator();
System.out.println("6! = "+ calc.factorial(6));
}
}

Output:

6! = 720

Garbage Collection and Memory Management:

In some languages, such as C++, you use the new operator to allocate new memory and then you use the delete operator to get rid of it when you don't need it anymore. However, Java does not have a delete operator.

In Java, you have to rely on a built-in process called garbage collection. This process occurs automatically, although you can't predict when it will happen. Java, itself, will dispose of allocated memory that on longer has any references to it. To make garbage collection happen, you can set any references to an item to null.

Ex.

class Data
{
public int intdata=0;
Data()
{
intdata=1;
}
}

public class app
{
public static void main( String[] args)
{
Data d=new Data();
// Some code ...
d=null;
// Some Additional code ...
}
}

Avoiding Circular References,

Ex. In this case, class a has an internal reference to an object of class b, and class b has an internal reference to an object of class a. When the code in main sets the reference it has to one of these objects to null, these objects will continue to sit in memory until the program ends.

class a
{
b b1;
a()
{
b1=new b();
}
}

class b
{
a a1;
b()
{
a1=new a();
}
}

public class app
{
public static void main( String[] args )
{
a obj = new a();
obj = null; // Inaccessible circular reference now exist!
}
}

Garbage Collection and The finalize Method:

The garbage collector will call a method named finalize in the object, if it exist. In the method, you can execute cleanup code and it's often a good idea to get rid of any reference to other objects that the current object has in order to eliminate the possibility of circular references.

class Data
{
public int intdata=0;
SuperGiantSizeClass sgsc;
Data()
{
intdata=1;
sgsc = new SuperGiantSizeClass(100000000);
}
protected void finalize()
{
sgsc = null;
}
}

public class app
{
public static void main( String[] args )
{
Data d =new Data();
d = null;
}
}

Overloading Methods:

Method Overloading is an object-oriented technique that lets you define several different versions of a method, all with the same name, but each with a different parameter list.

Ex.

class Calculator
{
int addem( int opt1, int opt2)
{
return opt1+opt2;
}

int addem( int opt1, int opt2, int opt3)
{
return opt1+opt2+opt3;
}
}

public class app
{
public static void main(String[] args)
{
Calculator calc=new Calculator();

System.out.println("addem(2,2) = "+ calc.addem(2,2));
System.out.println("addem(2,2,2) = "+ calc.addem(2,2,2));
}
}

Output:

addem(2,2) = 4
addem(2,2,2) = 6

Overloading Constructors:

Overloading constructors works like overloading other methods. You just define the constructor a number of times, each time with a parameter list with parameters that differ from the other lists in some way.

Ex.

class data
{
private String data_string;
data( char[] c)
{
data_string = new String(c);
}
data( String s)
{
data_string = s;
}
public String getData()
{
return data_string;
}
}

public class app
{
public static void main(String[] args)
{
char chararray[]={'H','e','l','l','o'};
System.out.println(new data(chararray).getData());
System.out.println(new data("Hello from Java!").getData());
}
}

Output:

Hello
Hello from Java!

Passing Object to Methods:

When you pass an item of a simple data type to a method, Java passes a copy of the data in the item, which is called passing by value. Because the method only gets a copy of the data item, the code in the method can't affect the original data item at all.

However, when you pass an object to a method, Java actually passes a reference to the object, which is called passing by reference. Passing by reference means that the code in the method can reach the original object. In fact, any changes made to the passed object affect the original object.

Ex. We pass an object of class Data to the print method of the printer class in order to print out the data in the object.

class Data
{
public String data_string;
Data( String data)
{
data_string = data;
}
}

class printer
{
public void print(Data d)
{
System.out.println(d.data_string);
}
}

public class app
{
public static void main( String[] args)
{
Data data=new Data("Hello from Java!");
printer p=new printer();
p.print(data);
}
}

Output:

Hello from Java!

Ex. We pass an object of the Data class to a method named rewrite that changes the data_string instance variable in the object. This variable starts out with the string "Hello from Java!" in it, but the rewrite method is able to change the string to "Hello to Java!" in this code.

class Data
{
public String data_string;
Data( String s)
{
data_string = new String(s);
}
}

class Class
{
public void rewrite( Data d)
{
d.data_string = "Hello to Java!";
}
}

public class app
{
public static void main( String[] args)
{
Data d=new Data("Hello from Java!");
Class c=new Class();
c.rewrite(d);
System.out.println(d.data_string);
}
}

Output:

Hello to Java!