Thursday, September 26, 2013

Java : Small GUI application Frame,Panel and Button Click (Ver 1.0)

Java : Small GUI application Frame,Panel and Button Click (Ver 1.0)

 

https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html
http://www.codeproject.com/Articles/33536/An-Introduction-to-Java-GUI-Programming
http://www.wikihow.com/Create-an-Executable-File-from-Eclipse
http://www.java2s.com/Code/Java/Swing-JFC/Buttonactiontochangethepanelbackground.htm
// Use JDialog instead of JFrame for thread to pause until an event




package start;
import java.awt.event.*;//ActionListener;
import javax.swing.*;

public class Test
{
    public static void main(String[] args)
    {
        GUI Test1=new GUI();
        JFrame oFrame=Test1.Create_Panel();
       
        //Anonymous inner class
        Test1.Button.addActionListener(new ActionListener(){ 
                        public void actionPerformed(ActionEvent e){ 
               JOptionPane.showMessageDialog(null, "Button Pressed"); 
                        }});
    }
}

//http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
  class GUI extends JFrame {
    JPanel Panel;
    JFrame Frame;
    JButton Button;
    JLabel Label;
   
    public JFrame Create_Panel()
    {   
        this.Frame=new JFrame("FrameDemo");                    //Frame
        this.Panel=new JPanel();                            //Panel
        this.Button=new JButton("Hi");                        //Button
       
        Button.setSize(20, 30);
        Panel.setSize(20, 30);
        Frame.setSize(100, 100);
               
        Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    /*Optional: when the frame closes?*/
        Panel.add(Button);                                        //Panel<-Button
        Frame.add(Panel);                                        //Frame<-Panel
                                        //Frame<-Panel<-Button
        Frame.setVisible(true);                                    //Show it.
        return Frame;
    }
}

Java: Anonymous Inner class




Anonymous Inner class

 

Note :Used in conjunction with Abstract Class or Interfaces

Example :

public class Test1 {

    public static void main(String[] args) {

        x obj=new x(){
                void disp() {System.out.println("Hi");}
                };
        obj.disp();
    }

}


abstract class x{   
    abstract void disp();
}

 

 Output: Hi

 


Use it as a shortcut for attaching an event listener:

Example:

button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)

    {

        // do something.

    }

});


  • Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener --
  •  I can just instantiate an anonymous inner class without actually making a separate class.
  • I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.



Java : Abstract Class VS Interfaces


Abstract Class VS Interfaces

 

 


Abstract Class VS Interfaces
Inheritance :

class animal{
void eat(){System.out.print("animal eat");}
}

class dog extends animal {
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat(); // instance dog can inherit animal property
}
}


Abstract Class :

abstract class animal{
void eat(){System.out.print("animal eat");}
abstract void noise(); // No definition
}

//dog class can inherit all properties except method declared as abstract
//Abstract method needs to be defined explicitly in the subclass ie., dog

class dog extends animal {
void noise(){System.out.print("bark");}
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat();
d.noise();
}
}

Ref : http://www.javacoffeebreak.com/faq/faq0084.html
To summarise:
1.Use abstract classes- can inherit all methods except ones declared as abstract.Abstract method should be declared explicitly in the calling method Ex :all animals eat,sleep but make different sound(sound can be made abstract which is explicitly defined in subclass)

2.Use interfaces - here all methods are abstract by default and everything has to be implemented (once implemented gives you a skeleton on things needs to be defined )
Interface:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.


/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}


/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){System.out.println("Mammal eats"); }

public void travel(){ System.out.println("Mammal travels");}

public int noOfLegs(){return 0; }

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}



4) NOTE:
Using an abstract class, you can have functions, that dont need to get implemented by the classes inheriting the abstract class. (http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
Using an interface, every subclass has to define every method, provided by this interface. (http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
Use an abstract class when you want to make one or more methods not abstract.
If you want to keep all abstract, use an interface.
5) Links
http://www.javatpoint.com/abstract-class-in-java
http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/

--------------------------------------------------
Uses of Interface
One reason I use interfaces is because it increases the flexibility of the code. Let's say we got a method that takes an object of class type Account as parameter, such as:

public void DoSomething(Account account) {
// Do awesome stuff here.
}

The problem with this, is that I have to send only Account object as a parameter.
Take this below example, which instead uses an account of type= Interface as parameter.

public void DoSomething(IAccount account) {
// Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SavingsAccount or a JointAccount or CurrentAccount (both who has implemented the IAccount interface ie., ) and get different behavior for each implemented account.

------------------------------------------------------------------------------------------

Uses of Interface

One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

class Animal
{
void walk() { }
....
.... //other methods and finally
void chew() { } //concentrate on this
}
Now, Imagine a case where:

class Reptile extends Animal
{
//reptile specific code here
} //not a problem here
but,

class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew but Bird classes can also call chew() method which is unwanted

Better design would be:

class Animal
{
void walk() { }
....
.... //other methods
}

Animal does not have the chew() method and instead is put in an interface as :

interface Chewable {
void chew();
}

and have Reptile class implement this and not Birds (since Birds cannot chew) :

class Reptile extends Animal implements Chewable { }

and in case of Birds simply:

class Bird extends Animal { }
-------------------------------------------------------
Rules for using Abstract ,Interface ,extending a class

Java interface is like a 100% pure abstract class.You MUST implement all abstract methods
Concrete class
-normal class - when your new class doesn’t pass the IS-A test for any other type.

When To extend a class ?
-when u need to add new behaviors and Passes IS-A.

How to implement Has -A functionality in an object ?
-Instance Variable or class variable
When To Use an abstract class -
A template for a group of subclasses and you have at least some implementation code that all subclasses could use.
when you want to guarantee that nobody can make objects of that type.
Abstract class uses methods as well as abstract methods

Use an interface -

when 100% abstract and static methods is allowed
when you want to define a role that other classes can play

--------------------------------------------------------
interface tree{
production();
}

class mango implements tree{
production(){}
}

class grape implements tree{
production(){}
}

psvm[]{
tree t=new mango();
tree t=new grape();
}

now user can create a new tree type like strawberry , orange etc., which has implement tree and use --
tree t=new orange();

ref:
http://catchbug.blogspot.in/2015/06/jave-excellent-interface-example.html