How to call a method dynamically using Java Reflection

In my previous post i have shown you how to create an instance dynamically using java reflection. Here i will show you how to call a method dynamically using reflection.

Let us start with a simple example. Assume that the method name is refreshForm and it has no argument. You can get the method using class.getMethod(methodName) method and then call the method using method.invoke(instance of the class) method.

 
String className = "com.commlink.cbs.appclient.gl.ChartsOfAccount"
String methodName = "refreshForm";

//get the Class
Class class = Class.forName(className);

// get the instance
Object obj = class.newInstance();

// get the method
Method method = class.getMethod(methodName );

//call the method
method.invoke(obj);


Things will be little complex if the method has some arguments. Suppose the refreshForm method takes two String values. To call this method using reflection first create an array of Class and then an array of Object. Use the class array in getMethod method and the Object array in invoke method in the following way.


String className = "com.commlink.cbs.appclient.gl.ChartsOfAccount"
String methodName = "refreshForm";
Class class = Class.forName(className );

Object obj = class.newInstance();

//create the class array
Class[] types = new Class[] { String.class,String.class};

//get the method
Method method = class.getMethod(methodName ,types);

//create the object array
Object[] args = new Object[]{new String("Hello"), new String("World")};

//call the method
method.invoke(obj,args);

How to create an instance of a class at runtime using Java Reflection

Java Reflection gives us the facility of creating an instance of any class at run time. In our ERP project it helps us a lot to solve some critical problems.

First create a class using the class name then use the class.newInstance method
to create an instance of that class.


javax.swing.JPanel newPanel = null;

String className= "com.commlinkinfotech.cbs.appclient.gl.ChartsOfAccount";

Class class = Class.forName(className);

//we know that the ChartsOfAccount is a JPanel class so cast this to JPanel
newPanel = (JPanel) class.newInstance();


But if the constructor of your class takes some parameters then what will you do?

You have to create an array of your argument class. Use this to create a constructor of your class using the class.getConstructor method. Now call the constructor.newInstance method with the value of the arguments and it gives you an instance of the class.


javax.swing.JPanel newPanel = null;

String className= "com.commlinkinfotech.cbs.appclient.gl.ChartsOfAccount";

//create an array of parameter classes
Class[] types = new Class[] { String.class };

Class class = Class.forName(className);
//create a constructor with the types array
Constructor constructor = class.getConstructor(types);

//create an array of argument values
Object[] args = new Object[] {new String("Hello")};

//now use ther args array to create an instance
newPanel = (JPanel) constructor .newInstance(args);

Understanding GroupLayout in Java

GroupLayout is one of the most effective layout managers in Java to place the GUI elements in a very organized way. Here I show you how to use Group Layout to build your GUI.

GroupLayout works with the horizontal and vertical layouts separately. The layout is defined for each dimension independently and it uses two types of arrangements -- sequential and parallel, combined with hierarchical composition. Usually, components placed in parallel in one dimension are in a sequence in the other, so that they do not overlap.

Let’s start with a very simple example to understand this layout.

Suppose you have to put one JLabel and one JTextField component in a row within a container named jpTestGroupLayout


You have to put these comonents both in a Horizontal sequential group and in a Vertical sequential group. But how?

To add the components in a horizontal sequential group at first you need to create two parallel groups. Add the JLable and the JTextField in the parallel groups then add these groups sequentially in the Horizontal sequential group.

And to add the components in a Vertical sequential group, create one parallel group and add the components in the group. Then add this parallel group to your vertical sequential group.

Now let’s look at the code to create the layout described above.


//declare the two component
JLabel label = new javax.swing.JLabel();
label.setText("JLabel");
label.setBorder(null);
JTextField jtfValue = new javax.swing.JTextField();
jtfValue.setText("JTextField");

//create a GroupLayout object associate with the panel
GroupLayout grpLayout = new GroupLayout(jpTestGroupLayout); jpTestGroupLayout.setLayout(grpLayout);
grpLayout.setAutoCreateGaps(true); // specify automatic gap insertion
grpLayout.setAutoCreateContainerGaps(true);

//create the Horizontal and Vertical and sequential group
GroupLayout.SequentialGroup horizontalSeqGrp = grpLayout.createSequentialGroup();
GroupLayout.SequentialGroup verticalSeqGrp = grpLayout.createSequentialGroup();

//create two parallel group for adding the components in the horizontal sequential group
GroupLayout.ParallelGroup hParallelGroup1 = grpLayout.createParallelGroup(GroupLayout.Alignment.LEADING);
GroupLayout.ParallelGroup hParallelGroup2 = grpLayout.createParallelGroup(GroupLayout.Alignment.LEADING);

//add the components
hParallelGroup1.addComponent(label);
hParallelGroup2.addComponent(textField);

//add two parallel groups sequentially in the horizontal sequential group
horizontalSeqGrp.addGroup(hParallelGroup1);
horizontalSeqGrp.addGroup(hParallelGroup2);

//create one parallel group for adding the components in the vertical sequential group
GroupLayout.ParallelGroup vparallelGroup1 = grpLayout.createParallelGroup(GroupLayout.Alignment.BASELINE);

//add the components
vparallelGroup1.addComponent(label);
vparallelGroup1.addComponent(textField);

//add this parallel group in the vertical sequential group
verticalSeqGrp.addGroup(vparallelGroup1);

//finally set the both sequential group to the grpLayout object
grpLayout.setHorizontalGroup(horizontalSeqGrp);
grpLayout.setVerticalGroup(verticalSeqGrp);


If you want to add another JLabel in the same row then what will you do?


It is very simple now. Just create another parallel group to add the new JLable in the Horizontal sequential group and to add this to the Vertical sequential group add this in the existing vertical parallel group.


JLabel label2 = new javax.swing.JLabel();
label2.setText("JLabel2");
label2.setBorder(null);
GroupLayout.ParallelGroup hParallelGroup3 = lout.createParallelGroup(GroupLayout.Alignment.LEADING);
hParallelGroup3.addComponent(label2);

//add the new parallel group to the horizontal sequential group
horizontalSeqGrp.addGroup(hParallelGroup3);
vparallelGroup1.addComponent(labe2l);


Now I describe another scenario. Suppose you want to add the second JLable in the following way.


The code will be like this


//add the new component in the hParallelGroup1
hParallelGroup1.addComponent(label2);

//create a new parallel group to add the new component in the vertical Sequential group
GroupLayout.ParallelGroup vparallelGroup2 = grpLayout.createParallelGroup(GroupLayout.Alignment.BASELINE);

//add the component to the new group
vparallelGroup2.addComponent(label2);

//add the new parallel group to the vertical sequential group
verticalSeqGrp.addGroup(vparallelGroup2);


Try the above examples yourself and definitely you will find this layout very easy to manage. For more information visit this link.

Filter a JTable row with input in a text field

In an enterprise application when there is huge amount data in a table
users feel comfortable if you provide them a option for filtering the
table. Here I show you an example of how to filter a JTable row with
input in a JTextField.

Declare a JTable and your own table model


private MyTableModel tableModel;
private javax.swing.JTable jtblSampleTable;


Now declare a table row sorter for that table model


private TableRowSorter sorter ;
//


Initialize all the above three declared variables


jtblSampleTable = new javax.swing.JTable();
tableModel = new MyTableModel();
sorter = new TableRowSorter(tableModel);
//


Bind the model with the table


jtblSampleTable.setModel(tableModel);


Set the sorter as the row sorter for the table


jtblSampleTable.setRowSorter(sorter);


Now declare a JTextField


jtfSearch = new javax.swing.JTextField();


Add a document listener for the search text field.


jtfSearch.getDocument().addDocumentListener(
new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
newFilter();
}
public void insertUpdate(DocumentEvent e)
{
newFilter();
}
public void removeUpdate(DocumentEvent e)
{
newFilter();
}
}
);



Here is the newFilter method


private void newFilter()
{
RowFilter< MyTableModel , Object> rf = null;
//declare a row filter for your table model
Try
{
rf = RowFilter.regexFilter("^" + jtfSearch.getText(), 0);
//initialize with a regular expression
}
catch (java.util.regex.PatternSyntaxException e)
{
return;
}
sorter.setRowFilter(rf);
}



The above example is able to filter JTable for its first column.

Show video from YouTube in your own website

To show a video from your website, first upload the video in YouTube.
After uploading the vidio add the following code in your website.


<object style="width: 360; height: 250; margin-top: auto; margin-bottom: auto; vertical-align: middle;">

<param name="movie" value="http://www.youtube.com/v/r-gDDUcaVqI&hl=en&fs=1>
</param>

<param name="allowFullScreen" value="true"> </param>

<embed src="http://www.youtube.com/v/r-gDDUcaVqI&hl=en&fs=1 type="application/x-shockwave-flash" allowfullscreen="true" width="360" height="250">
</embed>

</object>



In the param tag the value attribute holds the url of your video.
To change the display screen size simply change the width and height attribute
of the embed tag.

This is very simplet just copy and paste the code in your site and test it..

Creating a colorful rounded cornered Div

Rounded corner is one of the hottest topics in today’s web designing. Here you find a nice way of creating different colored rounded div. In my example, I have created one green and one yellow div.

The required css is


b.r1{margin: 0 5px}
b.r2{margin: 0 3px}
b.r3{margin: 0 2px}
h4,p{margin: 0 10px}

/*for yellow div*/
div#yellow_div{
margin: 0 5%;
background: #F7FC62;
/*change color here to get a different color div */
}
b.rtop_yellow, b.rbottom_yellow{display:block;background: #FFF}
b.rtop_yellow b, b.rbottom_yellow b{display:block;height: 1px;
overflow: hidden; background: #F7FC62}
/*change color here to get a different colored div */
b.rtop_yellow b.r4, b.rbottom_yellow b.r4{margin: 0 1px;
height: 2px}

/*for green div*/
div# green_div{
margin: 0 5%;
background: #8FFF63;
/*color changed */
}
b.rtop_green, b.rbottom_green{display:block;background: #FFF}
b.rtop_green b, b.rbottom_green b{display:block;height: 1px;
overflow: hidden; background: #8FFF63}
/*color changed */
b.rtop_green b.r4, b.rbottom_green b.r4{margin: 0 1px;
height: 2px}


Now you will find how to use this css to create two colorful div

<div id=" yellow_div " style="width:250px; ">
<b class="rtop_yellow"><b class="r1"></b><b class="r2"></b><b class="r3"></b>
<b class="r4"></b></b>
  place your content here<br>
  place your content here<br>
  place your content here<br>
<b class="rbottom_yellow"><b class="r4"></b><b class="r3"></b><b class="r2">
</b><b class="r1"></b></b>
</div>
<br>
<div id=" green_div " style="width:250px; ">
<b class="rtop_green"><b class="r1"></b><b class="r2"></b><b class="r3">
</b><b class="r4"></b></b>
  place your content here<br>
  place your content here<br>
  place your content here<br>
<b class="rbottom_green"><b class="r4"></b><b class="r3"></b><b class="r2">
</b><b class="r1"></b></b>
</div>



The result will be like this.



You can easily create you own color div just by changing the color in css I mentioned above
and use that name in div id and class attribute of b tag.

Showing your own custom dialog box in java

While developing our ERP application we need to show a list of
all accounts in a dialog box and upon selecting an account the
base form will be updated. For this we need our custom dialog
box to show the list of accounts. Here i give an example of how
can you show your own custom dialog box and get desired value on
closing the dialog.

At first i like to describe the custom dialog class.



import javax.swing.JDialog;
import javax.swing.JFrame;

/**
* @author ratul
*/
public class CustomDialog extends JDialog {

private javax.swing.JLabel jLabel1;
private javax.swing.JButton jbtOK;
private javax.swing.JTextField jtfInput;
private String inputString = "";

public CustomDialog(JFrame frame, boolean modal) {
super(frame, modal);
initComponents();
pack();
setLocationRelativeTo(frame);
setVisible(true);
}

private void initComponents() {

jbtOK = new javax.swing.JButton();
jtfInput = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();

setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jbtOK.setText("OK");
jbtOK.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jbtOKActionPerformed(evt);
}
});
add(jbtOK, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 190,
-1,-1));

jtfInput.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jtfInputKeyReleased(evt);
}
});
add(jtfInput, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 120,
160, 20));

jLabel1.setText("Input some text here:");
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 120,
-1, -1));
}

private void jbtOKActionPerformed(java.awt.event.ActionEvent evt)
{
this.dispose();
}

private void jtfInputKeyReleased(java.awt.event.KeyEvent evt)
{
inputString += evt.getKeyChar();
}

public String getInputText()
{
return inputString;
}

}



The CustomDialog class extends the JDialog class. The first
parameter of the constructor is the parent frame, second parameter
determines whether the parent frame is disabled or enabled when
the dialog box will be shown.

In the key released action of the text field i populate the inputString.
The dialog box can be closed either by clicking the 'OK' button or close
button of the top right corner. You can get the value of the input
field from the parent from by calling the public String getInputText() method.

Now i describe how to open your custom dialog box:
In the action handler of a button in the parent frame write the following code



CustomDialog cDialog = new CustomDialog(this, true);
this.jtfShowText.setText(cDialog.getInputText());



This will show the dialog box. Now Input some text on the text field
and close the dialog box. The input text will be shown in the text
field of the parent frame.

NB: use null or absolute layout to design the custom dialog box.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers