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.

Introduction to Java Persistence Query Language (JPQL)

The Java Persistence Query Language(JPQL) is one of the basic area of Java Persistence which allows you to write portable queries that work regardless of the underlying data store. It uses a SQL-like syntax to select objects or values based on entity abstract schema types and relationships among them. An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.

Here i describes some syntax of the language so that you can build
your own query in JPQL easily.

Lets start from a basic select query
SELECT p FROM Player p
This statement retrieves all players from Player entity.

Now write a query with WHERE clause and input parameter
SELECT DISTINCT p FROM Player p WHERE p.position = ?1
Retrieves players with the position specified. The DISTINCT keyword eliminates duplicate values. ?1 element denotes the input parameter of the query. Here position a persistent field of the Player Entity.

Select statement with named parameters
SELECT DISTINCT p FROM Player p WHERE p.position = :position AND p.name = :name
The WHERE clause compares the values of these fields with the
named parameters of the query, set using the Query.setNamedParameter
method. The query language denotes a named input parameter using
colon (:) followed by an identifier. The first input parameter is
:position, the second is :name.

At the time of writing Entity we relates one entity with another. Lets
talk about queries that navigate to related entities. One thing to
remember"Expressions can navigate to relationship fields (related
entities), but not to persistent fields"

SELECT DISTINCT p FROM Player p, IN(p.teams) t
Retrieves All players who belong to a team. The IN keyword signifies
that teams is a collection of the Player entity. The p.teams
expression navigates from a Player to its related Team. The period
in the p.teams expression is the navigation operator.

JOIN statement for the same query
SELECT DISTINCT p FROM Player p JOIN p.teams t

Another statement that serves the same purpose
SELECT DISTINCT p FROM Player p WHERE p.team IS NOT EMPTY

Navigating to single valued relationship field
SELECT t FROM Team t JOIN t.league l WHERE l.sport = 'soccer' OR l.sport ='football'

Navigating relationship field with input parameter
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.city = :city

Some times you need to traverse multiple relationships. Following query navigate over two relationships.
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.league = :league

To reach to a persistent field of league you can navigate by following way
SELECT DISTINCT p FROM Player p, IN (p.teams) t WHERE t.league.sport = :sport
Here sport is a persistent field of League. And you have to navigate from Player to League via Team.

After WHERE clause you have to use some conditional expression.
Lets talk about conditional expressions of JPQL
LIKE:
SELECT p FROM Player p WHERE p.name LIKE 'Mich%'

IS NULL:
SELECT t FROM Team t WHERE t.league IS NULL
Retrieves All teams not associated with a league.

IS EMPTY:
SELECT p FROM Player p WHERE p.teams IS EMPTY
Retrieves all players not belong to a team

BETWEEN:
SELECT DISTINCT p FROM Player p WHERE p.salary BETWEEN :lowerSalary AND :higherSalary

[NOT] MEMBER [OF]:(Determines whether a value is a member of a collection. The value and the collection members must have the same type):
SELECT o FROM Order o WHERE :lineItem MEMBER OF o.lineItems


[NOT] EXISTS:(Return true only if the result of the subquery consists of one or more values and is false otherwise):
SELECT DISTINCT emp FROM Employee emp WHERE EXISTS (SELECT spouseEmp FROM Employee spouseEmp WHERE spouseEmp = emp.spouse)

ALL and ANY:
The ALL expression is used with a sub-query, and is true if all the
values returned by the sub-query are true, or if the sub-query is empty.

The ANY expression is used with a sub-query, and is true if some of
the values returned by the sub-query are true. An ANY expression
is false if the sub-query result is empty, or if all the values returned
are false. The SOME keyword is synonymous with ANY.
The ALL and ANY expressions are used with the =, <, <=, >, >=, <>
comparison operators.
SELECT emp FROM Employee emp WHERE emp.salary > ALL (
SELECT m.salary FROM Manager m WHERE m.department = emp.department)


The following two queries tell you how to write UPDATE and DELETE
statement in JPQL
UPDATE Player p SET p.status = 'inactive' WHERE p.lastPlayed < :inactiveThr
DELETE FROM Player p WHERE p.status = 'inactive' AND p.teams IS EMPTY

Lets talk about aggregate functions of JPQL, Some frequently used aggregate functions are AVG, COUNT, MAX, MIN, SUM.
SELECT AVG(o.quantity) FROM Order o

SELECT SUM(l.price) FROM Order o JOIN o.lineItems l JOIN o.customer c WHERE c.lastname = 'Coss' AND c.firstname = 'Roxane'

In most cases after aggregate functions you have to use GROUP_BY or HAVING clause. but how to use them in JPQL? Here is the answer
SELECT c.country, COUNT(c) FROM Customer c GROUP BY c.country

SELECT c.status, AVG(o.totalPrice) FROM Order o JOIN o.customer c GROUP BY c.status HAVING c.status IN (1, 2, 3)

If you want to fetch data by your defined order then use ORDER_BY in the query
SELECT o FROM Customer c JOIN c.orders o JOIN c.address a WHERE a.state = 'CA' ORDER BY o.quantity, o.totalcost


Constructor expressions: It is an advance feature of JPQL. It allows you to return Java instances that store a query result element instead of an Object[]. The following query creates a CustomerDetail instance per Customer matching the WHERE clause. A CustomerDetail stores the customer name and customer’s country name. So the query returns a List of CustomerDetail instances.
SELECT NEW com.xyz.CustomerDetail(c.name, c.country.name) FROM customer c WHERE c.lastname = 'Coss' AND c.firstname = 'Roxane'

For more information about JPQL click here

How to create a Open flash chart in Rails Application

Open flash chart is a free service, by using it you can create different types of charts easily.

To create a open flash chart in Rails application at first you need
the open flash chart plugin. To get this plugin go to your project folder and run:
ruby script/plugin install http://svn.pullmonkey.com/plugins/trunk/open_flash_chart/

After this Move the open_flash_chart.swf file into your RAILS_ROOT/public directory

Now create a controller and add the following code


def index
@graph_data = open_flash_chart_object(450,220,
'/flash_chart/show_flash_chart',false,'/',true)
end



def show_flash_chart
begin
chart = draw_chart
render :text => chart
rescue Exception => error
logger.debug "error>>" + error.inspect
end
end



def draw_chart

chart_data = get_chart_data

#get data to display in chart
x_lebels = chart_data[:x_level]

# get x labels in a array
data = chart_data[:value]

# get y axis value
line_data_hashes = [{:color => "#e11456",
:legend => "Cost", :values => data}]
g = Graph.new

#draw line
if line_data_hashes
line_data_hashes.each do |line|
g.line(2, line[:color], line[:legend], 10)
g.set_data(line[:values])
end
end

g.set_tool_tip('Year: #x_label#
Cost: #val#')
g.set_title("Sample Flash Chart",
'{font-size: 14px; color: #784016}')

#set minimum y axis value
g.set_y_min(0)

#set maximum y axis value
g.set_y_max(100)

#set number of steps in y axis
g.set_y_label_steps(5)

# set y axis legend
g.set_y_legend("Cost", 12, "#b9d800")

# set x axix value
g.set_x_labels(x_lebels)

#set x axis label's style
g.set_x_label_style(10, '#000000', 2)

#set x axis legend
g.set_x_legend("Year", 12, "#b9d800")

return g.render

end


In index.rhtml put the following code

<%= @graph_data %>


Now run it and you will see the magic


How to run cruisecontrol.rb for continuous integration of Ruby on Rails application

CruiseControl.rb is a continuous integration tool for Ruby on Rails application. Its basic purpose is to alert members of a software project when one of them checks something into source control that breaks the build.

To run cruisecontrol.rb first download it from http://cruisecontrolrb.thoughtworks.com/
Unpack the downloaded file.
Then go to the folder from command prompt where it is unpacked
and run:
cruise add project_name --url (url of your subversion trunk)

This will create a directory under [cruise_data]/project/project_name and then checks out your project from the subversion URL you provided to [cruise_data]/projects/project_name/work/

Now run: cruise start
This will start your web browser on port 3333
Browse http://localhost:3333 and press the “Build Now” button on the Dashboard to build your project.

After this every time any one checks something into source control cruise control automatically
builds your project and report about the Build Changeset , Test failures and errors, etc.



Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers