January 31, 2012

right alignment in jtable cell


Example for right alignment of jtable cells in java swing



java.awt.Font font = new java.awt.Font("Serif", Font.BOLD, 12);
JTable table = new JTable();
searchResult_tbl.setAutoCreateRowSorter(true);
DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer();
tableCellRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
tableCellRenderer.setForeground(Color.BLACK);
tableCellRenderer.setFont(font);
table.getColumn("total").setCellRenderer(tableCellRenderer);
table.setGridColor(theme.getColorTableGrid());



Mastering the jtable see the tutorial

Eid Mubrak to all visitors

facebook page :  https://www.facebook.com

January 30, 2012

Printing TextPane in java

Java window application to print java textpane



package com.blog.javacode.print;
import javax.swing.JTable;
import javax.swing.JTextPane;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.MessageFormat;
public class PrintTextPane {
static MessageFormat headerMessage = new MessageFormat("java project source code");
static MessageFormat footerMessage = new MessageFormat("best java blog");
public static void main(String[] javacode) throws Exception {
PrinterJob printerJob = PrinterJob.getPrinterJob();
if(printerJob.printDialog()) {
JEditorPane jEditorPane = new JEditorPane("text/html", "text");
jEditorPane.read(new BufferedReader(new InputStreamReader(new FileInputStream(new File("belazy.html")))), "");
jEditorPane.repaint();
printerJob.setPrintable(jEditorPane.getPrintable(headerMessage, footerMessage));
printerJob.print();
}}}


The above example prints a java textpane with header and footer. user can define the header and footer here. Please post your valuable comments , after trying this code

Image reading and writting in java

Reading and writing an image file in java

Last day I want to copy some images from my digital camera to another ones, i copied all the images to that cameras memory card. Both the camera is of different companies, the camera is not displaying any images that i copied, i checked the folders are the same , its not because of the folder. then i noticed the images name, one is number while other is alpha numeric name, Since i had a 1000 of images to copy, renaming one by one seems to be very difficult for me and it will take around hours to complete the renaming process. What i did is i wrote a java program that rename each picture and save to another folder. The program was successful, now the image start displaying in that camera. Here is the program........

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;



public class RenameImageFiles {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("E:\\belazy");
System.out.println(f.list());
File [] list = f.listFiles();
System.out.println(list.length);
int num = 400;
for ( int i =0 ; i
String fileName = "PICT0"+num+".JPG";
System.out.println(list[i]);
BufferedImage bi = ImageIO.read(list[i]);
System.out.println(fileName+" .. "+ImageIO.write(bi, "JPG" ,new File("D:\\blazyjava\\"+fileName)));
num = num + 1;
}

}

}


January 07, 2012

How can ഐ add a Google search box to my Web site?

google search in your web application

java swing calendar

How to create a swing calendar in java.


Are you looking for a calendar in java swing, then here is the solution. The calendar works on java swing jframe

The use of calendar in java window as well as web application is inevitable.


java calendar for window application
Java swing calendar for window applications



/**
* Filename :Calendarium.java
* Author : belazy.blog.com
* Date : Sep 29, 2007
* Project Name : 
* Description : Display a calendar in java swing.
*/
package com.proximotech.kims.utils;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;



/**
* @see
* @author
* @author Seahawks
* @version 1.0
*/
public class Calendarium {
int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);;
JLabel l = new JLabel("", JLabel.CENTER);
String day = "";
JDialog d;
JButton[] button = new JButton[49];

public Calendarium(JFrame parent) {
d = new JDialog();
d.setModal(true);
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
JPanel p1 = new JPanel(new GridLayout(7, 7));
p1.setPreferredSize(new Dimension(430, 120));

for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
d.dispose();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
p1.add(button[x]);
}
JPanel p2 = new JPanel(new GridLayout(1, 3));
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
p2.add(previous);
p2.add(l);
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
p2.add(next);
d.add(p1, BorderLayout.CENTER);
d.add(p2, BorderLayout.SOUTH);
d.pack();
d.setLocationRelativeTo(parent);
displayDate();
d.setVisible(true);
}

/**
* @param panel_ins : instance of a panel
*
*
Description : This constructor is call the calendar
*
Date : Nov 8, 2011
*
Coded by : belazy..
*/
public Calendarium(JPanel panel_ins) {
d = new JDialog();
d.setModal(true);
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
JPanel p1 = new JPanel(new GridLayout(7, 7));
p1.setPreferredSize(new Dimension(430, 120));

for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
d.dispose();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
p1.add(button[x]);
}
JPanel p2 = new JPanel(new GridLayout(1, 3));
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
p2.add(previous);
p2.add(l);
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
p2.add(next);
d.add(p1, BorderLayout.CENTER);
d.add(p2, BorderLayout.SOUTH);
d.pack();
d.setLocationRelativeTo( panel_ins);
displayDate();
d.setVisible(true);
}



public void displayDate() {
for (int x = 7; x < button.length; x++)
button[x].setText("");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"MMMM yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, 1);
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
button[x].setText("" + day);
l.setText(sdf.format(cal.getTime()));
d.setTitle("CALENDAR");
}

public String setPickedDate() {
if (day.equals(""))
return day;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"dd-MM-yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, Integer.parseInt(day));
return sdf.format(cal.getTime());
}
}



how to create dynamic table in java

How to create a dynamic table in java

Description : The example show how to create a dynamic table using java swing, The code is developed using eclipse ide

/** DyanmicJTable
*
* version 1.0
*Aaron+Rodgers
*
*/
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Rectangle;
import javax.swing.JTextField;
import java.awt.GridBagLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import java.awt.GridBagConstraints;
import java.util.Vector;
/**
*
*/
/**
* @author vishnu
*
*/
public class DyanmicJTable extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JButton jButton = null;
private JTextField jTextField = null;
private JPanel jPanel = null;
private JScrollPane jScrollPane = null;
private JTable jTable = null;
private DefaultTableModel tableModel = null;
/**
* This is the default constructor
*/
public DyanmicJTable() {
super();
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(600, 600);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJButton(), null);
jContentPane.add(getJTextField(), null);
jContentPane.add(getJPanel(), null);
}
return jContentPane;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(218, 50, 176, 23));
jButton.setText("Add to table");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
Vector rowData = new Vector();
rowData.add(jTextField.getText());
tableModel.addRow(rowData);
System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
}
});
}
return jButton;
}
/**
* This method initializes jTextField
*
* @return javax.swing.JTextField
*/
private JTextField getJTextField() {
if (jTextField == null) {
jTextField = new JTextField();
jTextField.setBounds(new Rectangle(30, 49, 170, 26));
}
return jTextField;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJPanel() {
if (jPanel == null) {
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.gridx = 0;
jPanel = new JPanel();
jPanel.setLayout(new GridBagLayout());
jPanel.setBounds(new Rectangle(22, 105, 524, 214));
jPanel.add(getJScrollPane(), gridBagConstraints);
}
return jPanel;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(getJTable());
}
return jScrollPane;
}
/**
* This method initializes jTable
*
* @return javax.swing.JTable
*/
private JTable getJTable() {
if (jTable == null) {
tableModel = new DefaultTableModel();
tableModel.addColumn("Name");
String [] data = {"jhon duke"};
tableModel.addRow(data);
jTable = new JTable(tableModel);
}
return jTable;
}

public static void main(String[] args) {
    DyanmicJTable dynamicTable = new DyanmicJTable();
    dynamicTable.setVisible(true);
    dynamicTable.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

}

Description : Creating dynamic table (Grid) in java web application using javascript



Example

Java swing dynamic table example

create a dynamic table

Email validation in java

Email validator in java

How to validate an email address in using java regular expression. complete source code is available here. If you need to validate an email address through mail then we need to create a java web application.

  Here i created a function emailValidator with a parameter type string. the function will return true or false. call the function where ever you need it

/**
*
* @see
* @param
* @return boolean
* Description : email validator
* Date : Dec 4, 2009
* Coded by : belazy
*/
public boolean emailValidator(String email) {
boolean isValid = false;
String expression = “^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$”;
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}


Please try the code and provide us a feedback  

util to sql date and util from sql date conversion

util to sql date and util from sql date conversion

Description: This is an example for date parsing in java. Convert java util date to sql date. Java date convertor.

convertToSqlDate
/**
*
* @see example
* @param
* @return sqlDate java.sql.Date
*
Description : This function convert util date for sql Date. util date manipulation is used in user interface and sql date in back end process
* Date :Nov 12, 2009
* Coded by : belazy
*/
@Override
public java.sql.Date convertToSqlDate(Date utilDate) {
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
return sqlDate;
}
convertToUtilDate
/**
*
* @see
* @param
* @return
* Description :
* Date Dec 5, 2009
* Coded by : belazy
*/
@Override
public Date convertToUtilDate(java.sql.Date sqlDate) {
//java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
return utilDate;
}
Thanks to +aromal chandra for his support...

how to invoke system calculator in java

how to invoke system calculator in java


/**
*
* @see
* @param
* @return String
* Description : displayCalculator() displays system calculator on screen
*
* Date : Oct 31, 2009
* Coded by : +joseph james
*/
public String displayCalculator(){
Process process = null;
try {
process = Runtime.getRuntime().exec(“calc”);
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception exp){
JOptionPane.showMessageDialog(null, ” use Microsoft xp “);
}
return SUCCESS;
}

How to use string object in switch case

How to use string object in switch case


/**
* In Java SE 7 and later, you can use a String object in the switch statement’s expression
* Here is a small example
* If the string is null , it will throw a nullPointerException
* This is not the Best Java Programing Blog, I am just a learner in java
* Download jdk1.7 or above
*/
package com.nick.Switch;
import java.util.Scanner;
/**
* @author Oscar
*
*/
public class SwitchCaseString {
/**
* @param mon : denotes the first 3 char of month entered by the user
* @return month name
*/
private String getMonthName(String mon) {
String month = null;
switch (mon.toUpperCase()) {
case “JAN”: month =” its January “;
break;
case “FEB”: month =” its February “;
break;
case “MAR”: month =” its March “;
break;
case “APR”: month =” its April “;
break;
case “MAY”: month =” its May”;
break;
case “JUN”: month =” its June “;
break;
case “JUL”: month =” its Jully “;
break;
case “AUG”: month =” its August “;
break;
case “SEP”: month =” its September “;
break;
case “OCT”: month =” its October “;
break;
case “NOV”: month =” its November “;
break;
case “DEC”: month =” its December “;
break;
default:
month =” INVALID “;
break;
}
return month;
}
public static void main(String[] akshara) {
SwitchCaseString instance = new SwitchCaseString();
System.out.println(” Enter the first 3 character of the month “);
System.out.println(instance.getMonthName(new Scanner(System.in).next()));
}
}


Switch case example for practical question ( lab exams) 
Thanking you

TextField integer/Number validator in java swing

Example show how to create a text field in java swing that accepts only numbers
initializing variable

private JFormattedTextField expAmount_txt = null;
adding to container

panel.add(getExpAmount_txt(),null);
private JFormattedTextField getExpAmount_txt() {
if (expAmount_txt == null) {
Format general = NumberFormat.getInstance();
expAmount_txt = new JFormattedTextField(general);
expAmount_txt.setBounds(new Rectangle(120, 40, 120, 20));
expAmount_txt.setHorizontalAlignment(JFormattedTextField.RIGHT);
}
return expAmount_txt;
}



Thanking you..........

Positive Number chooser in java


How to create textfield in java that accept only positive integer value

This example shows a small demonstration of java text field that accepts only numbers. The project is developed in java swing.

import javax.swing.*;
/**
*
* @author James
*
*/
class PositiveNumberChooser {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SpinnerNumberModel numberModel = new SpinnerNumberModel(
new Integer(15), // value
new Integer(10), // min
new Integer(30), // max
new Integer(1) // step
);
JSpinner numberChooser = new JSpinner(numberModel);
JOptionPane.showMessageDialog(null, numberChooser);
System.out.println("Number: " + numberChooser.getValue());
}
});
}
}

Through this post i am introducing a blog for java developers name "belazy".  Need your feedback and comments. so please try the code ....

Facebook comments