Saturday, 15 April 2017

Swing Components and Containers

  • Swing contains two key items i.e components and containers.
  • Components are independent visual controls.
  • Conatiners builts a group of components.
  • Swing Containers  are of two types light-weight and heavy-weight.
    • All components of swing are derived from JComponent class.
    • JComponent do inherit component class and container class of awt.
    • JFrame, JApplet, JDialog and JWindow these are all swing containers but they do not inherit JComponent instead they directly inherit component and container class of awt.
    • Since awt is heavy-weight because it is platform independent, JFrame, JApplet, JDialog and JWindow do inherits awt component and container class and hece they are also heavy-weight.
    • Top-level containers are not containd within any other container.
    • All the swing component which inherits JComponent class are light-weight.
    • An example of light-weight container is JPanel which is a general purpose container.
    • Swing components are available in javax.swing package and some of the swing  events which are not defined in AWTEvent class are present in javax.swing.event  package

✭Swing components Constructor

  • JButton
  1. JButton();
  2. JButton(String str);
  3. JButton(ImageIcon image);
  4. JButton(String str, ImageIcon image);
  • JLabel
  1. JLabel();
  2. JLabel(String str);
  3. JLabel(Icon image);
  4. JLabel(String str, Icon image, int horizotalAlignment);
  5. JLabel(String str, int horizotalAlignment);
  • JRadioButton
  1. JRadioButton()
  2. JRadioButton(Action a)
  3. JRadioButton(Icon icon, boolean selected)
  4. JRadioButton(String text, boolean selected)RadioButton(String text, Icon icon)
  5. JRadioButton(String text, Icon icon, boolean selected)
  • JComboBox
  1. JComboBox()
  2. JComboBox(ComboBoxModel aModel)
  3. JComboBox(Object[] items)
  4. JComboBox(Vector<?> items)

Difference between Swing and AWT

  • Although awt is the curcial part of java, it's comoponent sets are not widely used to create GUI components nowadays.
  • Swing provides more powerfull and flexible GUI components than awt, hence today many programmers are using swing or javafx for building GUI based application.

  • The AWT also provides controls, dialog boxes, windows, containers which are useful, but with a limited graphical interface.

  • One reason for limited nature of AWT comnponents is that it translates it's various components into their corresponding, plat-form specific eqiuivalent or peers.

  • This means that the look and feel of an awt component is decided from it's native platform and not by java.

  • Because of these reasons AWT Components  are called heavy weight components.
NOTE :- AWT components are not fully created in java, this  is the reason they are called heavy-weight components. Whereas Swing components are fully created in java hence they are light-weight components.


  • Swing eliminates all the problem associated with awt by providing extra components like JTabbedPane, JTree etc.
  • Swing does not overcome awt, but it is build using the funtions of awt

✭ Key features of Swing

  1. Swing components are light-weight
    • Since the swing components are fully created in java, they do not convert their visual components into their corresponding/native platform peers. Means the look and feel is decided by java.
    • Thus, light -weight components are more flexible and more efficient.
      2. Swing supports plugable look and feel
    • As we discussed before that  the swing components are created in java and not by other programming languages, the look and feel is under the control of swing.
    • This, means that to seperate the look and feel from component logic and this what swing does.
    • Also swing can create a better look and feel on any platform, than awt because it contains pluggable(Means it can be attached easily) look and feel feature. 

Various event classes and their description


  • ActionEvent - It is generated when a button is pressed, a list item is double clicked or a menu item is selected.
  • ItemEvent - It is generated when checkbox, list item is clicked or when checkable menu item is selected or de-selected or even occurs when choice selection is made.
  • FocusEvent - It is generated when a component gains or looses the focus.
  • WindowEvent - It is generated when a window is activated, deactivate, opened, closed, closing, iconified, de-iconified.
  • MouseEvent - It is generated when a mouse is clicked, pressed, realesed, entered, exited.
  • MouseWheelEvent - It's generated when mouse wheel is moved.
  • KeyEvent - It is generated when a key pressed on the keyboard.
  • TextEvent - It is generated when the text value is changed in the textfield or textarea.
  • ContainerEvent - It is generated when a component is added oor removed from the container.]
  • ComponentEvent - It is generated when a component is resized, moved, hidden from a container.  
  • AdjustmentEvent - It is generated when scrollbar is manipulated.

Various abstract methods in Listeners interface

  • ActionLisener

  1. public void actionPerformed(ActionEvent ae) 
  • ItemListener

  1. public void itemStateChanged(ItemEvent ie)
  • WindowListener
  1. public void  windowClosed(WindowEvent we)
  2. public void windowOpened(WinowEvent we)
  3. public void windowActivated(WindowEvent we)
  4. public void windowDeactivated(WindowEvent we)
  5. public void windwIconified(WindowEvent we)
  6. public void windowDeiconified WindowEvent we)
  • WindowFocusListener
  1. public void windowGainedFocus(WindowEvent we)
  2. public void windowLostFocus(WindowEvent we)
  • FocusListener

  1. public void focusGained(FocusEvent fe)
  2. public void focusLost(FocusEvent fe)
  • MouseListener
  1. public void mouseClicked(MouseEvent me)
  2. public void mousePressed(MouseEvent me)
  3. public void mouseReleased(MouseEvent me)
  4. public void mouseEntered(MouseEvent me)
  5. public void mouseExited(MouseEvent me)
  • MouseMotionListener
  1. public void mouseDragged(MouseEvent me)
  2. public void mouseMoved(MouseEvent me)
  • MouseWheelListener
  1. public void mouseWheelMoved(MouseEvent me)
  • ContainerListener
  1. public void componenetAdded(ContainerEvent  ce)
  2. public void componentRemoved(ContainerEvent ce)
  • ComponenetListener

  1. public void componentHidden(CompomentEvent ce)
  2. public void componentResized(CompomentEvent ce)
  3. public void componentShown(ComponentEvent ce)
  4. public void componentMoved(ComponentEvent ce)

  • AdjustmentListener
  1. public void adjustmentValueChanged(AdjustmentEvent ae)
  • KeyListener

  1. public void keyPressed(KeyEvent ke)
  2. public void keyReleased(KeyEvent ke)
  3. public void keyTyped(KeyEvent ke)

Adapter Class

                As you can see above, most of the listeners are having are having more than one abstract method, in such case if you implement an interface then you have to override all of it's abstract methods, which is a part of good programming practise. So, to resolve this problem adapter class has been introduced, which contains empty implementation of all those listener interface which has more than one abstract method. Adapter class implements following type listener interfaces
  • WindowAdapter- for WindowListener
  • MouseAdapter - for MouseMotionListener, MouseListener
  • KeyAdapter - for KeyListener
  • ComponentAdapter - for ComponentListener
  • ContainerAdapter - for ContainerListener
  • FocusAdapter - for FocusListener
  • MouseMotionAdapter - for MouseMotionListener

Java AWT Event


  • Event classes are stored in java.awt.event package

Event handling mechanism

⟶Delegation Event Model

  • It is a modern approach.
  • It uses the concept of source and listener.
  • Source generates an event and sends it to one or more listeners.
  • Listener must register with the source to receive the event notification.
→Now what is an event?
  • An event is an object that describes state change in source.
  • for example:-   Suppose  a checkbox is registered with the ItemListener , so whenever the checkbox is selected or de-selected the state of the checkbox changes, therefore whenever the checkbox changes it's state it' s  listener is notified which in turn contains a method called itemStateChanged(ItemEvent ie) which has default parameter of ItemEvent object which in turn describes the event generated by the object.
→How to register a source with the listener
  • A source is an object that generates an event if there is some change in the internal state of that object.
  • To register a source with the listener addTypeListener(TypeListener object) method is used.
  • for example :- addActionListener(this), addItemListener(this)... like this way you can register components with their specified listeners. 
  • Here the TypeListener specifies object of class implementing listener interface.
  • for example :- To implementing ActionListener, addActionListener(new ActionListener(){public void actionPerformed(){}})
 →Explanation of  how an even occurs
  • When an even occurs all the registered listeners are verified. this is known as multi-casting the event.
  • Some sources may allow only one listener to register by using following method. addTypeListener(TypeListener obj)throws java.util.TooManyListenerException 
  • It is the type of uni-casting the listener.
  • To un-register with a specific type of event listener, you can use the following method public void removeTypeListener(TypeListener object).

→Event Classes

  • At the root of java event class hierarchy we have EventObject which is in package java.util.EventObject
  • EventObject class contains two methods getSource() and toString().
  • AWTEvent class belongs to java.awt package and is a sub-class of EventObject class
  • AWTEvent is a super class of all awt based events.
  • It has a function getId() which is used to determine the type of event. 

Summary

  • EventObject is super class of all events
  • AWT is super class of all awt based events
  • java.awt.event package defines various events generated  by various user interfaces.
                          

Friday, 6 January 2017

How Install Java and create Java environment.

  •           Open google chrome and type "download JDK latest version"

  • Click on the 5 link "Download Java Development Kit(JDK) - FileHippo.com" .
  • You can view a page like this. Then click on the green button "Download 64 bit(195.13MB)".
  • It will take about 15 to 20 minutes to get download.                                 

  • Open the file named "jdk-8u112-windows-x64" from downloads. A pop up will appear then click "Ok". After that your installation will start.
  • Then just click "Next" and it will give you a screen like this.



  • Wait just for few seconds till your installation completes.
  • After this installation a pop up will appear, then click on "Next". Then a window will appear as shown below.
.
  • After your installation is complete, you can see 2 files in your " c: drive", as  shown below in the highlighted.
  • Next right click on "This PC" or "my computer" and click "properties".




  • Click on "Advanced system settings".
  • Click on "Environment Variables", then click on "Edit".

  • This window will appear. Type "Variable name" as "Path" and copy the "directory" as followed in picture 2 into "Variable value".

picture 1

Picture 2


  • Then click "Ok". And our Java environment is successfully created 😉.





Wednesday, 4 January 2017

Explanation of Java with a simple program.


  •       This example is just displaying a string named "Hello World".



example:-

import java.lang.*; // Java defaultly import this package.

class hello //class name should be same as the file name you saved{
public static void main(String args[]){
System.out.println("Hello World");
}
}

Output:-











  • Let us elaborate this example, have a look at the very first line of program "import java.lang.*;". Java automatically import this package when ever you type your program. This package provides classes that are fundamental to the design of Java programming language, in this package the most important classes are object, which is the root of class hierarchy and class, instances of which represent classes at run time.
  • The second line of our program "class hello" which should be similar to the program file you created, because the JVM(Java Virtual Machine) compile your program based on the name of your class so it can give a similar byte code file".class". 
for example:-

  Output:-
In this example the compiler will generate the byte code but it won't be able to executed it and will give an error saying "Could find or load main class 'file name' " because the name of the file and class names are different.


  •  The third and the most important line to understand is "public static void main(String args[])".

Purpose of writing public to main()

          The main() is invoked  by JVM that stays outside the package of the class to which main() belongs. If main() is not declared as public then it won't be accessible outside the package and JVM cannot invoke it. Hence we wan't main() to be accessible outside package so it is declared as public

Purpose of writing static to main()

           If main() is not declared as static, then JVM will need to create  object main(). But since, main() is all entry point of Java program no objects are allowed to be created before main() is invoked. So we don not wan't main() to be invoked using object, hence it is declared as static. As to call static function object is not created.

Purpose of writing String args[]

           The "args[]" is an array whose type data type is String, in this array we can store various string arguments by invoking them at the command line for example:- myProgram Shaan Royal, then Shaan and Royal will be stored in the array as args[0] = "Shaan" and args[1] = "Royal". You can do this manually also inside the program, when don't call them at command line.


  •   The last line "System.out.println();" is an output statement, in which System is a class in the java.lang package. ".out" is a static member of System class, and is an instance of java.io.PrintStream, "println" is a method of java.io.PrintStream. This method is overloaded tom print message to output destination, which is typically a console or file.

Tuesday, 3 January 2017

Features of Java

  • Java has syntax similar to that of c,c++ making it easier of c, c++ programmers to learn
  • Java is platform independent i.e java programs compiled on one machine can be executed on any other machine having java environment.
  • Memory in java is automatically garbage collected by calling "System.gc()" function.
  • Java is fully object oriented programming language.
  • One of the most important feature of java is multi-threading, i.e each thread is a unit of execution and java can have multiple-thread which can be executed simultaneously("a thread is executed by CPU simultaneously and not by JVM").
  • Java is architecture-neutral, means if a java program is transferred  from one machine to another than change in OS,processor etc. won't force any change in java program.

Importance of learning Java programming language


  • Java is easy to learn for beginners.
  • Easier to maintain.
  • Java is object oriented programming language.
  • Java is platform independent.
  • Java is free.
  • Java has rich API.
  • Powerful development tools eg:- Eclipse, Netbeans, AndroidStudio.
  • Great collection of open source libraries.
  • Java is everywhere.
  • Excellent documentation support.         
  • 2nd most tagged language on GitHub.               

Monday, 2 January 2017

Introduction to Java



  • What is java?...  

                   Java is a programming language that evolved from a language named Oak. Oak was developed by Sun Microsystems in nineties as a platform independent  language aimed at allowing entertainment appliances such as video console and VCR's to communicate. It was originally
developed by "James Gosling" at Sun Microsystems and released in 1995 as a core component of Sun Microsystems Java platform.
James Gosling


                    The very first and most popular reason for learning java is that, it is platform independent. Now how Java is platform independent?. Since on every machine where java is installed creates an environment of it's own i.e creates a virtual machine on top of the underlying operating system. This virtual machine is called as JVM(Java Virtual Machine
                    
                    In java there is a JIT(Just In Time) compiler converts byte code to native machine code.
Hence a java program compiled on one machine can be executed on any another machine having java environment. So java is platform independent.

  • What is Byte Code in Java?
                   Byte code is the compiled form of java programs. Once java program is converted into byte code it can transferred over the network and can be executed on any another by Java Virtual Machine. Byte code files normally have a .class extension.

Java Working Diagram.
          
                      In this diagram it is clearly shown about the working of java. First a user understandable code is converted into byte code and then machine understandable code and finally it gets executed. Java can also be called as run time programming language.