Monday, March 15, 2010

Add dynamic content using Expression Tags in JSP

 

Its same as in fairy tales, once upon a time there where static pages ruling the web. And now, everyone is wishing to have content to be present according to the situation. Everything is live now. Dynamic content is what everyone wishes to see.

JSP pages are one which allow one to embed Java code to HTML. This is where we take advantage in creating dynamic content.

Expression Tag 

You need to embed your Java expressions in between <%= and %>

whatever is given in between, it is evaluated at run time.

Following is an example program…

<html>


    <head>        


        <title>JSP 1. Expression Tags</title>


    </head>


    <body>


        <div align="center">


        <h3>Current Time:</h3>


        <%= new java.util.Date() %>  <br/>


        <h4>Refresh the page to update the time !!!</h4>


        </div>


    </body>


</html>





 



Above code displays current time as and when page is refreshed.



So, now just search for reasons where you need to have dynamic content, like content is dependent on the users previous actions and etc..,

Tuesday, January 26, 2010

Observer Pattern | Advantage of it along with example

 

Well to be frank about his; I’m a newbie who doesn’t know about Design Patterns. I just came across this today while I was coding and one of my associates helped me with this pattern.

This example might be simple and even idiotic for those pro’s who are swimming in the Java world. This is for those beginners who need to know the spark in this concept ;)

One might think differently after going through this…. trust me… even if you don’t understand :P

Well I found info about this pattern over here, but I just took conceptual part from it.

Simply, the Observer pattern allows one object (the observer) to watch another (the subject). The Observer pattern allows the subject and observer to form a publish-subscribe relationship. Through the Observer pattern, observers can register to receive events from the subject. When the subject needs to inform its observers of an event, it simply sends the event to each observer.

For example, you might have a spreadsheet that has an underlying data model. Whenever the data model changes, the spreadsheet will need to update the spreadsheet screen and an embedded graph. In this example, the subject is the data model and the observers are the screen and graph. When the observers receive notification that the model has changes, they can update themselves.

This is what it had to say… ;)

Just another way,

Suppose you wanted the Panel to tell the frame to display a message box when a button has been pressed, the Panel will have to hold a reference to the frame class somewhere and then in its code call a method of the frame class when the button has been pressed. So now you have the frame holding a reference to the panel and a panel holding a reference to the frame which == tight coupling, which is a bad thing and can make it hard to debug or extend your program.

I think you got it…. If not comment it down…. :D

So, Let’s talk about business…

I will post regarding Anonymous classes ASAP…

This is a simple application which changes text of button in another panel. Text on button in second panel changes if an event occurs in first panel and vice versa.

Observer Pattern Example

Observer Pattern Example

Following is the code which explains this….

Main.java

package MyOwnListener;
/**
 * @author HUNTER
 * hunter4coding.blogspot.com
 */
 
public class Main {
 
public static void main(String[] args) {



new MightyFrame().setVisible(true);
}
}

MightyFrame.java

package MyOwnListener;
 
import java.awt.BorderLayout;
import javax.swing.*;
/**
 * @author HUNTER
 * hunter4coding.blogspot.com
 */
 
public class MightyFrame extends JFrame{
 
firstPanel firstSoldier = new firstPanel();
SecondPanel secondSoldier = new SecondPanel();
 
public MightyFrame(){
 
this.getContentPane().add(BorderLayout.NORTH, firstSoldier);
this.getContentPane().add(BorderLayout.CENTER, secondSoldier);



this.pack();
this.setLocation(300,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setResizable(false);
 



firstSoldier.addLordListener(new LordListener(){
 
public void playWithMe(String text) {



// You might want to share the resources 
// of the panel here in frame



//JOptionPane.showMessageDialog(MightyFrame.this, text);
 
if(secondSoldier.btnTwo.getText().equals("NO"))
secondSoldier.btnTwo.setText("YES");
else
secondSoldier.btnTwo.setText("NO");
 
}
});        
 
secondSoldier.addLordListener(new LordListener(){
 
public void playWithMe(String text) {
//JOptionPane.showMessageDialog(MightyFrame.this, text);



if(firstSoldier.btnOne.getText().equals("NO"))
firstSoldier.btnOne.setText("YES");
else
firstSoldier.btnOne.setText("NO");
}
});
}
}

firstPanel.java

package MyOwnListener;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
 * @author HUNTER
 * hunter4coding.blogspot.com
 */
 
 
public class firstPanel extends JPanel{
 
JButton btnOne = new JButton("Yes");



public firstPanel(){
 
this.add(btnOne);        
 
// Adding ActionListener to 'btnOne'
btnOne.addActionListener(new ActionListener(){
 
public void actionPerformed(ActionEvent e) {
littleTestOne();
}
});



}
 
// Panel event occurs here
private void littleTestOne(){        
this.listener.playWithMe("U CLICKED " + btnOne.getText());
}
 
private LordListener listener;
 
public void addLordListener(LordListener listening){
this.listener = listening;
}



}

secondPanel.java

package MyOwnListener;
 
import java.awt.event.*;
import javax.swing.*;
/**
 * @author HUNTER 
 * hunter4coding.blogspot.com
 */
 
public class SecondPanel extends JPanel{
 
JButton btnTwo = new JButton("NO");
 
public SecondPanel(){
 
// Adding ActionListener to 'btnTwo'
btnTwo.addActionListener(new ActionListener(){
 
public void actionPerformed(ActionEvent e) {
littleTestTwo();
}
});
 
this.add(btnTwo);
}
 
// Panel event occurs here
private void littleTestTwo(){
this.listener.playWithMe("U CLICKED " + btnTwo.getText());
}
 
private LordListener listener;
 
public void addLordListener(LordListener listening){
this.listener = listening;
}
 
}

 

LordListener.java

package MyOwnListener;
/**
 * @author HUNTER 
 * hunter4coding.blogspot.com
 */
 
public interface LordListener {
public void playWithMe(String text);
}

Monday, January 18, 2010

Adding, Removing and Changing Components in Panel | Java Swing

Recently I faced this problem of changing the components of the panel I’m using. I found this solution and thought of sharing it.

Adding, Removing componets from JPanel


Following is the code…

Main.java
   1: package changepanel;
   2:  
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  * http://hunter4coding.blogspot.com/
   6:  */
   7: public class Main {
   8:  
   9:     public static void main(String[] args) {
  10:         new TestFrame().setVisible(true);
  11:     }
  12: }

TestFrame.java

   1: package changepanel;
   2:  
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  * http://hunter4coding.blogspot.com/
   6:  */
   7: import java.awt.BorderLayout;
   8: import javax.swing.JFrame;
   9: import java.awt.event.ActionEvent;
  10: import java.awt.event.ActionListener;
  11:  
  12: public class TestFrame extends JFrame{
  13:  
  14:     FirstPanel firstPanel = new FirstPanel();
  15:     SecondPanel secondPanel = new SecondPanel();
  16:  
  17:     public TestFrame(){
  18:  
  19:         this.getContentPane().add(BorderLayout.NORTH, firstPanel);
  20:         this.getContentPane().add(BorderLayout.CENTER, secondPanel);
  21:  
  22:         this.setSize(250, 150);
  23:         this.setLocation(250, 250);
  24:         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  25:         this.setResizable(false);
  26:  
  27:         firstPanel.btnFirst.addActionListener(new BtnListener());
  28:     }
  29:  
  30:  
  31:     class BtnListener implements ActionListener{
  32:  
  33:         public void actionPerformed(ActionEvent e) {
  34:  
  35:             // REMOVE ALL THE COMPONENTS
  36:             //secondPanel.removeAll();
  37:  
  38:             // REMOVE RESPECTIVE COMPONENT
  39:             secondPanel.remove(secondPanel.btnSecond);
  40:             // BOTH WILL WORK HERE !!!
  41:  
  42:             // ADD THE NEW COMPONENT
  43:             secondPanel.add(secondPanel.lblMsg);
  44:  
  45:             // THIS IS INTRESTING PART...
  46:             secondPanel.revalidate();
  47:             secondPanel.repaint();
  48:         }
  49:     }
  50: }

FirstPanel.java

   1: package changepanel;
   2:  
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  * http://hunter4coding.blogspot.com/
   6:  */
   7: import javax.swing.JButton;
   8: import javax.swing.JPanel;
   9:  
  10: public class FirstPanel extends JPanel{
  11:  
  12:     JButton btnFirst = new JButton("Click me");
  13:  
  14:     public FirstPanel(){
  15:         this.add(btnFirst);
  16:     }
  17: }


SecondPanel.java

   1: package changepanel;
   2:  
   3: /**
   4:  * @author HUNTER4U AKA SRIHARSHA
   5:  * http://hunter4coding.blogspot.com/
   6:  */
   7: import javax.swing.JButton;
   8: import javax.swing.JLabel;
   9: import javax.swing.JPanel;
  10:  
  11: public class SecondPanel extends JPanel{
  12:  
  13:     JButton btnSecond = new JButton("I'll Vanish !!!");
  14:     JLabel lblMsg = new JLabel("I ate ur BUTTON :P");
  15:  
  16:     public SecondPanel(){
  17:         this.add(btnSecond);
  18:     }
  19: }

Well following is the explanation for revalidate() and repaint() I read while browsing the web.

  1. invalidate()/validate()/revalidate() only affects the layout. It results in a repaint if the layout actually changes.
  2. invalidate()/validate() is the mechanism for batching changes (like beginPaint, paint, paint, paint, endPaint of windowing SDKs). You mark, using invalidate(), all the components that might affect the layout as invalid. Then call the parent container's validate() method. In the validate() method the parent checks if at least one of its immediate children is invalid. If it finds a child marked invalid, it calls layoutComponents() on its layout manager.

    If the layoutmanager actually re-lays out the children, then, as a side effect, repaint() will get called.

    The thing to note here is that the Container only looks for invalid immediate children.

    For precisely this reason sometimes the resulting layout is not what you expected as the parent's parent and children's chidren may not get re-layed out. To work around this issue Swing added the revalidate() method.

  3. What revalidate() does is basically marks all the container upto the top level (window and its subclasses or applet) as invalid. Then it calls validate() on the top level.

Hope it helped you ;)