Sandeep & Vicky’s Archive » java

Archive for the ‘java’ Category

Hi,

The following code connects to an access database “multilingual.mdb” located in the default folder of the java code. It does not requires to create a dsn for the same

CODE

try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String myDB = “jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=multilingual.mdb”;
Connection c = DriverManager.getConnection(myDB,”",”");

Statement s=c.createStatement();

ResultSet rss=s.executeQuery(“select naam from table1 where id=1″);

rss.next();
String st=rss.getString(1);

System.out.println(“string=”+st);
}
catch (Exception ex)

{
ex.printStackTrace();
}

Hi People, The following is my analysis on the Pricing and Promotion strategies of Sun Microsystems.

Pricing Strategy followed by Sun Microsystems: Java

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems’ Java platform.

Java is an Open Source Language .i.e. One does not have to Pay Sun Microsystems for downloading the Source code of Java. But then the Questions is: How does Sun Microsystems generate revenue from Java?

In 1996, Sun created Java and the terms under which it is distributed. Since then, the Java Community Process (JCP) has emerged, allowing companies to participate in shaping language changes, but the ownership of trademarks, licensing agreements, branding, and other fundamental product issues remains unchanged. One is reminded of this fact every time the Sun MicrosystemsTM trademark appears alongside the Java coffee cup logo, or when one is greeted with the message “brought to you by Sun Microsystems” at www.java.com. For anyone to use the Java-compatible logo on a product requires verification against the test compatibility kit (TCK), for which one has to enter into negotiations with Sun. Java, the technology, the trademark, and the language, are owned by Sun.

The current licensing agreements for Java generate revenue for Sun in two ways; one is through direct fees to its licensees, and the other is through indirect revenue generated off the back end of Java’s success.

Besides the above Java also generates revenue by conducting certificate programs and certifications exams like SCJP, SCJD, etc. Clearing these examinations is just like getting a degree which shows that the degree holder has a good knowledge of Java and these certifications are very important for an IT Personnel’s CV. Sun Microsystems charges around 7200 INR for these examinations

When asked how much income is generated from Java, Jonathan Schwartz, CEO of Sun, replied, “about $13 billion.”

Conclusion

Thus Sun Microsystems have not priced their actual product, but they have priced the services that people would require after using their product.

The reason Sun Microsystems could do this is that there a very few competitors in the market and in spite of the competition, Java is the best among them.

Promotion Strategy followed by Sun Microsystems: Java

Promotion through developers

Prior to java there were many programming languages for different Operating systems, Examples include C, C++, FoxPro, Visual Basic, etc. But there was one major common problem with all these languages; these languages were Platform Dependent .i.e. They had to be compiled differently on different Operating Systems .i.e. If a developer develops a code in C language and compiles the code on say Windows Operating System, then that code would not work on Linux Operating system, thus increasing the burden of the developer to compile the code again for Linux and Other Operating System.

Thus there was a great demand for a Programming Language that is Platform independent during the 1990’s. Sun Microsystems soon captured this Niche Segment of the Developers through its Platform Independent Language Java. On top of that the source code of Java was made open source to the developers all over the world. Any developer could download the source code from the website of Sun and use the code free of cost. Sun Microsystems used the fastest means of distribution .i.e. the Internet as their distribution Channel.

The main idea behind making the source code open source was to push the brand to the developers. Sun Microsystems was aware of the fact that the developers will in turn push the brand to many customers and enterprises, thus creating a cumulative effect, and Sun would earn through Licensing and Certifications. That is what Sun Microsystems is doing these days.

Sun Microsystems has also started a Developer network (SDN) to solve the problem faced by the developers that are using Java. This is to give their target audience a better service and support.

Promotion through software applications and Web servers

Soon after the launch of Java, Sun Microsystems also launched its Internet surfing browser Netscape Navigator which was developed totally on the Java Programming language. This move was taken to show the developers the extent to which Java can be used and how developers can add new features in their software using Java.

Sun Microsystems also developed a Web server called Apache Tomcat server to handle web requests in the form of HTTP. This also facilitated the promotion of Java, as the server was built on the Java Platform. (Please note that: A web server is a computer with equipped softwares where the web sites are hosted).

Again, all these facilitated pushing the Java brand to the Developers which was Sun Microsystems’ Main target.

Publicity

Soon after the launch, the Java source code became very popular among the developers. Many people started discussion forums, blogs & eLearning websites on Java Programming on the Internet. Thus, Java gained a lot of Publicity through its developer network and soon became very popular. Also, the increasing popularity of Java triggered the publishing of articles on Java in the Newspaper and online News portals like Forbes Newsletter, etc.

Conclusion

Thus, Sun Microsystems targeted only the Developer network and pushed the brand to Developers who in turn pushed it to the rest of the world.

I was trying to set default focus to a textfield which was placed in a joptionpane, but it wast working with the following code

cvendor.requestFocus();

whereas the same code worked perfectly when the textfield was placed in a jpanel. On research i found that the default focus in a joptionpane is always on the OK button and it cannot be changed statically, it can only b changed during runtime using the Runnable interface. Here is the code that did the trick

javax.swing.SwingUtilities.invokeLater(new Runnable() {//<—–add
public void run() { cvendor.requestFocus(); }});//<—-add

nn=JOptionPane.showConfirmDialog(null,Jop,”Please enter details”,JOptionPane.CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);

kool na………..

30
Sep

Accessing windows registry using java

   Posted by: admin

Hi guys,

You can edit, change or delete any windows registry key values using java.

All you need to do is download d JNI interface for Windows registry from the following link

Click  JNI Registry to download the package

This package has many classes through which we can access the registry.

It is a very simple code and  very interesting. It is a two step process: First convert the double to string and then convert the string to int. Here is the code for the same:

CODE

double d=198.17;

int i=0;

String stotat= “”+d; // Convert double to string

i=Integer.parseInt(stotal.substring(0,stotal.indexOf(“.”))); // convert string to int.

System.out.println(“Integer=”+i);

//  thats is….put it in a class to see it working

//jai Convergence (www.convergenceservices.in)

Hey guys if you want a code which will convert a number to its word format then here is the code you are looking for. This one is normally used in a lot of banks and places where there is a hell lot of economic transactions. For example a billing software would obviously require this. It does the foll

929 = Nine hundered twenty nine

So, here is the code

public class NumWord {
String string;
String a[]={“”,
“one”,
“two”,
“three”,
“four”,
“five”,
“six”,
“seven”,
“eight”,
“nine”,
};

String b[]={
“hundred”,
“thousand”,
“lakh”,
“crore”

};

String c[]={“ten”,
“eleven”,
“twelve”,
“thirteen”,
“fourteen”,
“fifteen”,
“sixteen”,
“seventeen”,
“eighteen”,
“ninteen”,
};

String d[]={

“twenty”,
“thirty”,
“fourty”,
“fifty”,
“sixty”,
“seventy”,
“eighty”,
“ninty”
};

public String convertNumToWord(int number){

int c=1;
int rm ;
string=”";
while ( number != 0 )
{
switch ( c )
{
case 1 :
rm = number % 100 ;
pass ( rm ) ;
if( number > 100 && number % 100 != 0 )
{
display ( “and ” ) ;
}
number /= 100 ;

break ;

case 2 :
rm = number % 10 ;
if ( rm != 0 )
{
display ( ” ” ) ;
display ( b[0] ) ;
display ( ” ” ) ;
pass ( rm ) ;
}
number /= 10 ;
break ;

case 3 :
rm = number % 100 ;
if ( rm != 0 )
{
display ( ” ” ) ;
display ( b[1] ) ;
display ( ” ” ) ;
pass ( rm ) ;
}
number /= 100 ;
break ;

case 4 :
rm = number % 100 ;
if ( rm != 0 )
{
display ( ” ” ) ;
display ( b[2] ) ;
display ( ” ” ) ;
pass ( rm ) ;
}
number /= 100 ;
break ;

case 5 :
rm = number % 100 ;
if ( rm != 0 )
{
display ( ” ” ) ;
display ( b[3] ) ;
display ( ” ” ) ;
pass ( rm ) ;
}
number /= 100 ;
break ;

}
c++ ;
}

return string;
}

public void pass(int number)
{
int rm, q ;
if ( number < 10 )
{
display ( a[number] ) ;
}

if ( number > 9 && number < 20 )
{
display ( c[number-10] ) ;
}

if ( number > 19 )
{
rm = number % 10 ;
if ( rm == 0 )
{
q = number / 10 ;
display ( d[q-2] ) ;
}
else
{
q = number / 10 ;
display ( a[rm] ) ;
display ( ” ” ) ;
display ( d[q-2] ) ;
}
}
}

public void display(String s)
{
String t ;
t= string ;
string= s ;
string+= t ;
}

public static void main(String args[]){

NumWord num=new NumWord();
System.out.println(“num.convertNumToWord(0)”+num.convertNumToWord(Integer.parseInt(args[0])));

}

}

OUTPUT :

Whatever number you pass as command line argument would be converted to its word format.

It does not actually requires programming. All you need to do is call the appropriate API, that will do the job for you. The followin code will help you to convert a date from one format to another

CODE

String reverseDate(String date)
{// date is of the format yyyy-mm-dd
java.text.DateFormat dfYMD =
new java.text.SimpleDateFormat(“yyyy-MM-dd”) ;
java.text.DateFormat dfDMY =
new java.text.SimpleDateFormat(“dd-MM-yyyy”) ;
try
{
return dfDMY.format(dfYMD.parse(date)) ;

}
catch (Exception e)
{
e.printStackTrace();
return “00-00-0000″;
}
}

we all know what are 2D arrays, they are just array of arrays, Here is a simple code which can help you if u are interseted in navigating through the 2D array in search of some keyword or string. The following is the function which will ease your job

public MatCell contains(String search, String[][] searchtable,int row,int cell)
{
boolean found = false;
boolean searchrow = true;
int cellcounter = 0;
int cellcount =0;
try
{
cellcount = searchtable[0].length;

}
catch (ArrayIndexOutOfBoundsException e)
{
// if the array is not initialised
cellcount = 0;
System.out.println(“Array not initialised”);
}

//        int row = 0;
//        int cell = 0;
int ROWDIM=searchtable.length-1;

int[] cellhit = new int[ROWDIM];

while(!found)
{
MatCell mat=new MatCell();
while(searchrow)
{
if(cellcount == cell)
{
cell = 0;
searchrow = false;
}
else
{
//System.out.println(“Array value:”+searchtable[row][cell]);
if(searchtable[row][cell]!=null)
{
if((searchtable[row][cell]).toLowerCase().contains(search.toLowerCase()))
{
mat.row=row;
mat.col=cell;

//    System.out.println(“Found “+searchtable[row][cell]);
found = true;
return(mat);
}
}
cell++;
}
}
row++;
searchrow = true;
if(row==ROWDIM)
{
System.out.println(“Search not found.”);
found = true;    // return true value to break the loop;
}
}
return null;
}

CLASS MATCELL

class MatCell
{
int row=0;
int col=0;
};

9
May

java code to search a string in a jTable.

   Posted by: admin

Hi guys, If you are looking for a search and replace program like the one provided by MS Office, Dreamweaver, and every other High end application, then you have come to the right place. The following code will help you to search a particular string or a word in a JTable.

If you are developing something like a spreadsheet or excel sheet in java, then this will surely help you in searching those big documents, or 2D arrays.

You can customize it for search and replace as well.

CODE

import javax.swing.*;
import javax.swing.table.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.text.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.util.Calendar;

import javax.swing.table.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.text.MessageFormat;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.io.*;

class MatCell
{
int row=0;
int col=0;
};

public class TablePrint
{
//Printable tp;

static String ovr=”";

int drow,arow;

TableColumn cl;
static void printFrame(Object rs[][],Object hd[],String m)
{

final String mm=m;
final Object rows[][]=rs;

final Object headers[] = hd;
Runnable runner = new Runnable() {

public void run() {
final JFrame frame = new JFrame(“Convergence Printing. www.convergenceservices.in”);
DefaultTableModel model = new DefaultTableModel(rows,headers);

final JTable table = new JTable( model )
{
//  Returning the Class of each column will allow different
//  renderers to be used based on Class
public Class getColumnClass(int column)
{

return getValueAt(0, column).getClass();
}

};
table.setPreferredScrollableViewportSize(table.getPreferredSize());

table.setShowGrid(false);

table.setSize(620,500);

table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

if(mm.equalsIgnoreCase(“1″))    // for receipts
{

final JTextField search=new JTextField(10);
JPanel p=new JPanel();
JButton button1 = new JButton(“Find next”);
ActionListener findAction = new ActionListener() {
int startrow=0;
int startcol=0;

public void actionPerformed(ActionEvent e)
{
String mat[][]=getStringArray(table);

/*    for (int i=0;i<mat.length ;i++ )
{
for (int j=0;j<mat[0].length ;j++ )
{
System.out.print(“\t”+mat[i][j]);
}
System.out.println();
}
*/        String    key = search.getText();
MatCell m= contains (key, mat, startrow,startcol);

if (m!=null)
{
search.setBackground(Color.white);

startrow=m.row;
startcol=m.col;
System.out.println(“Row=”+startrow);
System.out.println(“Col=”+startcol);

boolean toggle = false;
boolean extend = false;
table.changeSelection(startrow, startcol, toggle, extend);
//        startrow+=(m.row+1)%mat[0].length;
startcol=(m.col+1)%mat[0].length;
if (startcol==0)
{
startrow++;
}

System.out.println(” New Row=”+startrow);
System.out.println(” New Col=”+startcol);
}
else
{
startrow=0;
startcol=0;
table.clearSelection();
search.setBackground(Color.red);
Toolkit.getDefaultToolkit().beep();
}

//If a string was returned, say so.
}
public MatCell contains(String search, String[][] searchtable,int row,int cell)
{
boolean found = false;
boolean searchrow = true;
int cellcounter = 0;
int cellcount =0;
try
{
cellcount = searchtable[0].length;

}
catch (ArrayIndexOutOfBoundsException e)
{
// if the array is not initialised
cellcount = 0;
System.out.println(“Array not initialised”);
}

//        int row = 0;
//        int cell = 0;
int ROWDIM=searchtable.length-1;

int[] cellhit = new int[ROWDIM];

while(!found)
{
MatCell mat=new MatCell();
while(searchrow)
{
if(cellcount == cell)
{
cell = 0;
searchrow = false;
}
else
{
//System.out.println(“Array value:”+searchtable[row][cell]);
if(searchtable[row][cell]!=null)
{
if((searchtable[row][cell]).toLowerCase().contains(search.toLowerCase()))
{
mat.row=row;
mat.col=cell;

//    System.out.println(“Found “+searchtable[row][cell]);
found = true;
return(mat);
}
}
cell++;
}
}
row++;
searchrow = true;
if(row==ROWDIM)
{
System.out.println(“Search not found.”);
found = true;    // return true value to break the loop;
}
}
return null;
}

public String[][] getStringArray(JTable jt)
{
String s[][]=new String[jt.getRowCount()][jt.getColumnCount()];

for (int i=0;i<s.length ;i++ )
{
for (int j=0;j<s[0].length ;j++ )
{
s[i][j]=”"+jt.getValueAt(i,j);
}
}

return s;
}

};
button1.addActionListener(findAction);
search.addActionListener(findAction);
p.add(search);
p.add(button1);

button1.setMnemonic (KeyEvent.VK_F);
frame.add(p, BorderLayout.NORTH);

boolean opt=true;
String str=”";

try {
BufferedReader in = new BufferedReader(new FileReader(“printoption.bat”));
String str1=”";
while ((str1 = in.readLine()) != null) {
str=str1;
}
in.close();
} catch (IOException e) {
}

System.out.println(“str=”+str);
if (str.equalsIgnoreCase(“use”))
{
opt=true;
}
else
{
opt=false;
}
opt=true;
int vColIndex1 = 0;

if (opt)
{
table.getColumnModel().getColumn(vColIndex1).setHeaderValue(new ImageIcon(“images/logo.jpg”));
table.getColumnModel().getColumn(vColIndex1).setHeaderRenderer(new TableCellRenderer());

}
int width1 = 500;
table.getColumnModel().getColumn(vColIndex1).setPreferredWidth(width1);

table.setRowHeight(20);
frame.setBounds(400,35,620, 550);

}

JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton(“Print”);

ActionListener printAction = new ActionListener() {

public void actionPerformed(ActionEvent e)
{
table.clearSelection();

try{
//JTable table = new JTable(myModel);
PrinterJob job =PrinterJob.getPrinterJob();
MessageFormat headerFormat = new MessageFormat(“”);
MessageFormat footerFormat = new MessageFormat(“”);

Paper pap=new Paper();

pap.setImageableArea(0,500,468,771);

PageFormat pg=job.defaultPage();

pg.setPaper(pap);

System.out.println(“Width=”+pg.getImageableWidth());
System.out.println(“Height=”+pg.getImageableHeight());
Printable    tp=new TablePrintable1(table,JTable.PrintMode.FIT_WIDTH, headerFormat,footerFormat);
job.setPrintable(tp,pg);

if (job.printDialog())
{
job.setJobName(“Theo Printing”);

job.print();
}

}

catch (PrinterException pe)
{System.err.println(“Error printing: “);}

frame.dispose();
}

};
button.addActionListener(printAction);
button.setMnemonic (KeyEvent.VK_P);
frame.add(button, BorderLayout.SOUTH);

frame.setVisible(true);
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
frame.setLocationRelativeTo(null);
}
};
EventQueue.invokeLater(runner);

ovr=”1″;

}

public static void main(String arg[])
{
Calendar c=Calendar.getInstance();
Object chargedata[][]=new Object[16][1];
for (int j=0;j<chargedata.length ;j++ )
{
chargedata[j][0]=”";
//        chargedata[j][1]=”";
}

int j=0;
chargedata[j++][0]=”";
chargedata[j++][0]=”<html><h3>Transaction id :                                     Receipt                                Date : “+c.get(Calendar.DAY_OF_MONTH)+”-”+(c.get(Calendar.MONTH)+1)+”-”+c.get(Calendar.YEAR)+” </h3></html>”;

chargedata[j++][0]=”                                                                                                   “;
chargedata[j++][0]=”RECEIVED with thanks from”;
chargedata[j++][0]=”<html><h4>Mr./Mrs./Ms     </h4></html>”;
chargedata[j++][0]=”<html><h4>Rs.     only,  by </h4><html>”;
chargedata[j++][0]=”towards the following “;
chargedata[j++][0]=”<html><h4>                                         Particulars                                                                                                                       INR </h4></html>”;
//added for theo
chargedata[j++][0]=”<html><h4>———————————————————————————————————————————————————————–</h4></html>”;
chargedata[j++][0]=”Pooja Offering                                                                                                                                                      “;
chargedata[j++][0]=”<html><h4>———————————————————————————————————————————————————————–</h4></html>”;
chargedata[j++][0]=”<html><h3>Date of Pooja : . Time (24 hrs): </h3></html>”;
chargedata[j++][0]=”<html><h6>*Cheque subject to realisation</h6></html>”;
chargedata[j++][0]=”";
chargedata[j++][0]=”";
chargedata[j++][0]=”<html><h4>                                                                                                                                                                 Treasurer </h4></html>”;

String hd[]={“”};

TablePrint.printFrame(chargedata,hd,”1″);

}

///////////////////————————–
}

OUTPUT

search.JPG

Hey guys, this one’s kool. I have been into java programming for the past two years but discovered this simple logic now, after such a long time.

You all are aware of 2D arrays or matrix. We may visualize it like a 2D matrix some what like this

1 2 3

4 5 6

7 8 9

But actually internally in java, this is an Array of arrays. In this particular example, the main array being an array of three more arrays, the child arrays

array 1 : 1 2 3

array 2 :4 5 6

array 3 : 7 8 9

So we can always find the number of colums of a 2D array or a matrix by finding the length of the child arrays.

This code will help u in doing that

String array[][]=new String[100][5];

int nocols =0 ;

try
{
nocols = array[0].length; // array [0] is a child array of our main 2d array
}
catch (ArrayIndexOutOfBoundsException e)
{
// if the array is not initialised
nocols = 0;
System.out.println(“Array not initialised”);
}
And to find the number of  rows in a 2d array, the following code will help u

int norows=array.length;

jai Convergence.

Related Posts with Thumbnails