public class RoundTwoDecimalPlaces{
public static void main(String[] args) {
float num = 2.954165f;
float round = Round(num,2);
System.out.println("Rounded data: " + round);
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
public static double Round(double Rval, int Rpl) {
double p = (double) Math.pow(10, Rpl);
Rval = Rval * p;
//double tmp = Math.round(Rval);
double tmp = Math.floor(Rval);
return (double) tmp / p;
}
}
Thursday, December 30, 2010
Rounding off in Java - Round two decimal places
Monday, December 27, 2010
To avoid JTextField copy in Java
public void avoidTxtFieldCopy(JTextField mytextfield)
{
JTextComponent.KeyBinding[] newBindings = {
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
DefaultEditorKit.beepAction),
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
DefaultEditorKit.beepAction),
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
DefaultEditorKit.beepAction)
};
Keymap k = ();
JTextComponent.loadKeymap(k, newBindings, mytextfield.getActions());
Keymap k1 = Obj_Name.getKeymap();
JTextComponent.loadKeymap(k1, newBindings, Obj_Name.getActions());
}
Tuesday, December 7, 2010
MySQL DB tuning
In installation directory
Ex: C:\Program Files\MySQL\MySQL Server 5.0
open my (Configuration Settings) file then
we need to change as per our table creation type MyISAM/INNODB
Ex: For MyISAM below properties need to change as per our requirement
myisam_max_sort_file_size=100G
myisam_max_extra_sort_file_size=100G
myisam_sort_buffer_size=60M
key_buffer_size=26M
read_buffer_size=64K
read_rnd_buffer_size=512K
sort_buffer_size=512K
then you will feel real difference
Friday, December 3, 2010
Drag and Drop between two Table(Java Swing)
I followed below steps,
* Creating two(table1 and table2) non editable table with single selection(drag and drop for single cell values).
* In table1 only C and D column only u can drop.
* table2 drop cell is empty then table1 drag value drop in table1 and that value will deleted from table2.
* drop cell is not empty then existing table1 value will be added to table2.
My program as below
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
/**
* DADTableDemo : Example of drag and drop option between two tables
* @author R.Amirtharaj
*/
public class DADTableDemo {
/** Main Frame */
public JFrame myframe = new JFrame("Drag and drop demo");
/** Table 1*/
public JTable table1 = new JTable();
/** Table 2*/
public JTable table2 = new JTable();
/** Table1 Model */
public DefaultTableModel tm1 = new DefaultTableModel(0, 5) {
public boolean isCellEditable(int row, int col) {
return false;
}
};
/** Table2 Model */
public DefaultTableModel tm2 = new DefaultTableModel(0, 5) {
public boolean isCellEditable(int row, int col) {
return false;
}
};
/** Table1 ColumnNames */
public String[] proptbtitle1 = {"A", "B", "C(Drop will allow)", "D(Drop will allow)", "E"};
/** Table2 ColumnNames */
public String[] proptbtitle2 = {"Z"};
// Constructor
public static void main(String args[])
{
DADTableDemo demo = new DADTableDemo();
demo.create();
}
// create Drag and Drop demo
public void create()
{
JPanel pan = new JPanel();
// Table 1 related
tm1.setColumnIdentifiers(proptbtitle1);
table1.setModel(tm1);
table1.getTableHeader().setReorderingAllowed(false);
addTable1Details();
table1.setDragEnabled(true);
table1.setDropMode(DropMode.ON);
table1.setSelectionMode(0);
table1.getTableHeader().setReorderingAllowed(false);
// Add DAD
TransferHandler dnd1 = getDND1();
table1.setTransferHandler(dnd1);
// add table1 to scrollpane
JScrollPane sp1 = new JScrollPane(table1);
// add to panel
pan.add(sp1);
// Table 1 related
tm2.setColumnIdentifiers(proptbtitle2);
table2.setModel(tm2);
table2.getTableHeader().setReorderingAllowed(false);
addTable2Details();
table2.setDragEnabled(true);
table2.setSelectionMode(0);
// Add DAD
TransferHandler dnd2 = getDND2();
table2.setTransferHandler(dnd2);
// add table1 to scrollpane
JScrollPane sp2 = new JScrollPane(table2);
// add to panel
pan.add(sp2);
// add to frame
myframe.getContentPane().add(pan);
myframe.pack();
myframe.setVisible(true);
}
/**
* Table1 details
*/
public void addTable1Details()
{
String str[][] = {{"aaa", "bbb", "", "", "eee"},
{"fff", "ggg", "hhh", "iii", "jjj"}};
for(int i=0;i
} else {
return false;
}
int intcol = dcol.getColumn();
// Allowing drop only for C and D column for Table 1
if (intcol != 2 || intcol != 3) {
return false;
}
// fetch the data and bail if this fails
String data;
try {
data = (String) support.getTransferable().getTransferData(
DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
System.out.println("data = "+data);
if (intcol == 2) {
// if field is not empty existing value will add in Table 2
if (table1.getValueAt(row, 2) != null && !table1.getValueAt(row, 2).toString().equalsIgnoreCase("")) {
String strEID = table1.getValueAt(row, 2).toString();
// adding table2
tm2.addRow(new String[]{strEID});
}
table1.setValueAt(data, row, intcol);
table1.repaint();
}
else if (intcol == 3) {
// if field is not empty existing value will add in Table 2
if (table1.getValueAt(row, 3) != null && !table1.getValueAt(row, 3).toString().equalsIgnoreCase("")) {
String strEID = table1.getValueAt(row, 3).toString();
// adding table2
tm2.addRow(new String[]{strEID});
}
table1.setValueAt(data, row, intcol);
table1.repaint();
}
return true;
}
};
return dnd1;
}
/**
* TransferHandler for Table2
* @return TransferHandler for Table2
*/
public TransferHandler getDND2() {
TransferHandler dnd2 = new TransferHandler() {
public int getSourceActions(JComponent comp) {
return MOVE;
}
private int index = -1;
// dad data reference
String transferData = "";
public Transferable createTransferable(
JComponent comp) {
index = table2.getSelectedRow();
// fetching selected data
transferData = table2.getValueAt(table2.getSelectedRow(), 0).toString();
return new StringSelection(transferData);
}
public void exportDone(JComponent comp, Transferable trans, int action) {
if (action != MOVE) {
return;
}
tm2.removeRow(index);
}
};
return dnd2;
}
}
Wednesday, December 1, 2010
GeneralizedHashMap
public class GHashMap {
public ArrayList alUid = new ArrayList();
public ArrayList al1 = new ArrayList();
public ArrayList al2 = new ArrayList();
public void add(String strUid,String str1,String str2)
{
alUid.add(strUid);
al1.add(str1);
al2.add(str2);
}
public String getValue1(String strUid)
{
String strVal1 = null;
if(alUid.contains(strUid))
{
int intIndex = alUid.indexOf(strUid);
strVal1 = al1.get(intIndex).toString();
}
return strVal1;
}
public String getValue2(String strUid)
{
String strVal2 = null;
if(alUid.contains(strUid))
{
int intIndex = alUid.indexOf(strUid);
strVal2 = al2.get(intIndex).toString();
}
return strVal2;
}
public String getUid(String strVal1,String strVal2)
{
String strid = null;
if((al1.contains(strVal1)) && (al1.contains(strVal1)))
{
int size = al1.size();
for(int i=0;i
if(al1.get(i).equals(strVal1))
{
if(al2.get(i).equals(strVal2))
{
strid = alUid.get(i).toString();
}
}
}
}
return strid;
}
}
Thursday, November 25, 2010
HashMap Iteration
// ArrayList
public static void dumpList(ArrayList al)
{
Iterator
itr = al.iterator ();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
}
//Hash Set
public static void Set(HashSet hs)
{
Iterator
itr = hs.iterator ();
while (itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
}
// HashMap
public static void dumpMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
Monday, October 11, 2010
In Java , programeticlly how to Compile and create JAR?
// import
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
try {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// set ur java file path
int result = compiler.run(null, null, null, "BaseClass/Hello.java");
}
catch(Exception e)
{
e.printStackTrace();
}
For Jar creation
try {
String command = "jar cvf MyFirst.jar BaseClass" + File.separatorChar;
Process p = Runtime.getRuntime().exec(command);
}
catch (Exception ex) {
ex.printStackTrace();
}
Monday, September 27, 2010
Why Map is not under Collection interface?
How to Use an object as key for a hashmap in Java?
I taken example as a ‘Person’ in a network, with my constructor looking something like the following:
public Person(String name) {
this.name = name;
}
now I use the following overrides:
public int hashCode()
{
return name.toString().hashCode();
}
public boolean equals(Object o) {
Person person = (Person)o;
if (person.name.equals(name))
{
return true;
}
return false;
}
and when i’m testing whether a particular key exists in the hashmap, I can create a new Person and check directly whether it currently exists as a key in the hashmap. Typically, if you didn’t implement this, then two person objects would have different references (even if they have the same name) and would not be equal.
File size in Java
public class FileSize {
public static void main(String[] args) {
//create file object
File file = new File("C://FileIO/demo.txt");
/*
* To get the size of a file, use
* long length() method of Java File class.
* This method returns size of a particular file in bytes. It returns 0L
* if file does not exists, and unspecified if file is a directory.
*/
long fileSize = file.length();
System.out.println("File size in bytes is: " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
}
}
Sunday, September 5, 2010
How to get Date and Time Format in java?
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Friday, September 3, 2010
Can't start Server within 50 seconds from Eclipse. How to increase the Time out value?
Eclipse gave the following error when I tried to run a jboss server for my webservice application.
Server JBoss v5.0 at localhost was unable to start within 50 seconds. If the server requires more time, try increasing the timeout in the server editor.
Fine, increase the time in server editor.. should be straight forward, I thought.. but then, I can't find a time out field to change the value...
After a minute or so, it turned out that you need to double click on the server that appears in the "Servers" tab("Servers" tab usually appears next to the "Console" tab). When you double click, a new window is opened in the main editor and then, Expand the "Timeouts" section..
Now I can change the 'Start time out value' to 300, then its worked fine....
Friday, August 27, 2010
String split in java
/*
Java String split example.
This Java String compare example describes how Java String is splited into multiple Java String objects.
*/
public class JavaStringSplitExample{
public static void main(String args[]){
/*
Java String class defines following methods to split Java String object.
String[] split( String regularExpression )
Splits the string according to given regular expression.
String[] split( String reularExpression, int limit )
Splits the string according to given regular expression. The number of resultant substrings by splitting the string is controlled by limit argument.
*/
/* String to be splitted. */
String str = "one-two-three";
String[] temp;
/* delimeter */
String delimeter = "-";
/* given string will be splitted by the argument delimeter provided. */
temp = str.split(delimeter);
/* print splitted substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
/*
IMPORTANT : Some special characters needs to be escaped while providing them as delimeters like "." and "|".
*/
System.out.println("");
str = "one.two.three";
delimeter = "\\.";
temp = str.split(delimeter);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
/*
Using second argument in the String.split() method, we can control the maximum number of substrings generated by splitting a string.
*/
System.out.println("");
temp = str.split(delimeter,2);
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
}
}
/*
OUTPUT of the above given Java String split Example would be :
one
two
three
one
two
three
one
two.three
*/
Friday, August 13, 2010
How to get the size of ResultSet (total number of rows/columns)?
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
To Get RowCount:
1. Using Query
// Get a record count with the SQL Statement
Statement stmt = connection.createStatement();
String strQry = "SELECT COUNT(*) AS rowcount FROM Person";
ResultSet rs = stmt.executeQuery(strQry);
rs.next();
// Get the rowcount column value.
int ResultCount = rs.getInt(rowcount) ;
rs.close() ;
2. Using Scrollable ResultSet:
String strQuery = "SELECT * FROM Person";
// Create a scrollable ResultSet.
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(strQuery);
// Point to the last row in resultset.
rs.last();
// Get the row position which is also the number of rows in the ResultSet.
int rowcount = rs.getRow();
System.out.println("Total rows for the query: "+rowcount);
// Reposition at the beginning of the ResultSet
rs.beforeFirst();
Thursday, July 15, 2010
Measuring time(in ms) for particular operation in java
public static void main(String arg[])
{
long startOperation = System.currentTimeMillis();
// Some operation
long endOperation = System.currentTimeMillis();
long timeTaken = endOperation - startOperation;
//long timeTaken = System.currentTimeMillis()-startOperation;
System.out.println("Time taken = "+timeTaken+" ms");
}
}
Iterator Demo
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Tuesday, June 29, 2010
Comparing two dates in JAVA
import java.util.Calendar;
public class MyDate {
public static void main(String[] args) {
Calendar c1=Calendar.getInstance();
c1.set(2009,22,05);
Calendar c2=Calendar.getInstance();
c2.set(2009,23,05);
if(c1.compareTo(c2)<0)
{
// return -1 if date1 is less than date2
System.out.println("1. Date1 is less than date2");
}
else if(c1.compareTo(c2)>0)
{
// return 1 if date1 is greater than date2
System.out.println("1. Date1 is greater than date2");
}
else
{
// return 0 if date1 is equal to date2
System.out.println("1. Date1 is equal to date2");
}
/**
* Compare date with after(), before() and equals() method
*/
if(c1.after(c2))
{
// if date1 is greater than date2
System.out.println("2. Date1 is greater than date2");
}
else if(c1.before(c2))
{
// if date1 is less than date2
System.out.println("2. Date1 is less than date2");
}
else if(c1.equals(c2))
{
// if date1 is equal to date2
System.out.println("2. Date1 is equal to date2");
}
}
}
Example programs of Collection
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList
//
arlist.add("First Element"); // adding element in ArrayList
arlist.add("Second Element");
arlist.add("Third Element");
arlist.add("forth Element");
arlist.add("fifth Element");
// add element with index for fix order
arlist.add(2, "Fixed Order of Element");
// arlist.size() inform number of elements in ArrayList
System.out.println("ArrayList Size :"+arlist.size());
// get elements of ArrayList
for(int i=0;i
// duplicate element is not permitted
hs.add("b");
hs.add("a");
hs.add("c");
hs.add("d");
hs.add("d");
Iterator it=hs.iterator();
while(it.hasNext())
{
String value =(String)it.next();
System.out.println("Value :"+value);
}
//find size of hashSet
System.out.println("Size :"+hs.size());
// Remove element from hashSet :
hs.remove("d");
// To remove all object from hashSet
hs.clear();
}
}
HashTableExample :
import java.util.Hashtable;
import java.util.Enumeration;
public class HashTableExample {
public static void main(String[] args) {
Hashtable
//adding or set items in Hashtable by put method key and value pair
hTable.put(new Integer(2), "Two");
hTable.put(new Integer(1), "One");
hTable.put(new Integer(4), "Four");
hTable.put(new Integer(3), "Three");
hTable.put(new Integer(5), "Five");
// Get Hashtable Enumeration to get key and value
Enumeration em=hTable.keys();
while(em.hasMoreElements())
{
//nextElement is used to get key of Hashtable
int key = (Integer)em.nextElement();
//get is used to get value of key in Hashtable
String value=(String)hTable.get(key);
System.out.println("Key :"+key+" value :"+value);
}
}
}
HashMapExample :
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
HashMap
Friday, June 25, 2010
How to make JTable cell not Editable?
Example:
public class MyTableModel extends AbstractTableModel{
public void isEditable()
{
return false;
}
}
Then you have a table and you set its model to a MyTableModel object
ex.
JTable table = new JTable();
table.setModel(new MyTableModel());
Write Text into File
import java.io.*;
public class WriteTextFileExample{
public static void main(String[] args)throws IOException{
BufferedWriter output = null;
String text = Amirtharaj;
// if 2nd arg is true then the file content append
FileWriter fstream = new FileWriter("write.txt", true);
output = new BufferedWriter(
fstream
);
output.write(text);
output.close()
}
}
Tuesday, June 22, 2010
Adding a external jar to an RCP application
Go to Runtime tab.
Click on 'Add...' button in the Classpath section
Add your external jar
As a result my MANIFEST.MF now has the entry
Bundle-ClassPath: lib/myjar.jar,
while my .classpath has the entry
classpathentry kind="lib" path="lib/myjar.jar"
Friday, June 11, 2010
DragandDrop in JTable
This class is implemented to provide a default behavior of transferring a component property simply by specifying the name of the property in the constructor. For example, to transfer the foreground color from one component to another either via the clipboard or a drag and drop operation a TransferHandler can be constructed with the string "foreground". The built in support will use the color returned by getForeground as the source of the transfer, and setForeground for the target of a transfer.
For Example for JTable:
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.IOException;
public class DragandDrop extends JFrame {
public DragandDrop() {
setTitle("DnD Demo");
JTextArea tips = new JTextArea("1. Select a row in Table A. " +
"Press the row again and drag. \n " +
"As you drag the cursor icon over Table B, the row that is currently under the cursor highlights " +
"? the new data will be inserted after the selected row. \n " +
"Drop the row onto Table B. Note that the row has been removed from Table A, " +
"and now appears in Table B. \n" +
"2. Select two rows from Table A and drop onto Table B. " +
"Now there are two new rows in Table B. ");
tips.setEditable(false);
tips.setBackground(new Color(255, 255, 204));
tips.setBorder(new LineBorder(Color.orange, 5));
getContentPane().add(tips, BorderLayout.NORTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(createTable("Table A"));
panel.add(createTable("Table B"));
getContentPane().add(panel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel createTable(String tableId) {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Column 0");
model.addColumn("Column 1");
model.addColumn("Column 2");
model.addColumn("Column 3");
model.addRow(new String[]{tableId + " 00", tableId + " 01", tableId + " 02", tableId + " 03"});
model.addRow(new String[]{tableId + " 10", tableId + " 11", tableId + " 12", tableId + " 13"});
model.addRow(new String[]{tableId + " 20", tableId + " 21", tableId + " 22", tableId + " 23"});
model.addRow(new String[]{tableId + " 30", tableId + " 31", tableId + " 32", tableId + " 33"});
model.addRow(new String[]{tableId + " 40", tableId + " 41", tableId + " 42", tableId + " 43"});
model.addRow(new String[]{tableId + " 50", tableId + " 51", tableId + " 52", tableId + " 53"});
model.addRow(new String[]{tableId + " 60", tableId + " 61", tableId + " 62", tableId + " 63"});
model.addRow(new String[]{tableId + " 70", tableId + " 71", tableId + " 72", tableId + " 73"});
JTable table = new JTable(model);
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(400, 100));
table.setDragEnabled(true);
table.setTransferHandler(new TableTransferHandler());
scrollPane.getViewport().setTransferHandler(new ViewportTransferHandler());
JPanel panel = new JPanel();
panel.add(scrollPane);
panel.setBorder(BorderFactory.createTitledBorder(tableId));
return panel;
}
public static void main(String[] args) {
new DragandDrop().setVisible(true);
}
abstract class StringTransferHandler extends TransferHandler {
protected abstract String exportString(JComponent c);
protected abstract void importString(JComponent c, String str);
protected abstract void cleanup(JComponent c, boolean remove);
protected Transferable createTransferable(JComponent c) {
return new StringSelection(exportString(c));
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean importData(JComponent c, Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
try {
String str = (String) t.getTransferData(DataFlavor.stringFlavor);
importString(c, str);
return true;
} catch (UnsupportedFlavorException ufe) {
} catch (IOException ioe) {
}
}
return false;
}
protected void exportDone(JComponent c, Transferable data, int action) {
cleanup(c, action == MOVE);
}
public boolean canImport(JComponent c, DataFlavor[] flavors) {
for (int ndx = 0; ndx < flavors.length; ndx++) {
if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
return true;
}
}
return false;
}
}
class TableTransferHandler extends StringTransferHandler {
public JTable target;
public int[] rows = null;
public int addIndex = -1; //Location where items were added
public int addCount = 0; //Number of items added.
protected String exportString(JComponent c) {
JTable table = (JTable) c;
rows = table.getSelectedRows();
int colCount = table.getColumnCount();
StringBuffer buff = new StringBuffer();
for (int ndx = 0; ndx < rows.length; ndx++) {
for (int j = 0; j < colCount; j++) {
Object val = table.getValueAt(rows[ndx], j);
buff.append(val == null ? "" : val.toString());
if (j != colCount - 1) {
buff.append(",");
}
}
if (ndx != rows.length - 1) {
buff.append("\n");
}
}
return buff.toString();
}
protected void importString(JComponent c, String str) {
target = (JTable) c;
DefaultTableModel model = (DefaultTableModel) target.getModel();
int index = target.getSelectedRow();
//Prevent the user from dropping data back on itself.
//For example, if the user is moving rows #4,#5,#6 and #7 and
//attempts to insert the rows after row #5, this would
//be problematic when removing the original rows.
//So this is not allowed.
if (rows != null && index >= rows[0] - 1 &&
index <= rows[rows.length - 1]) {
rows = null;
return;
}
int max = model.getRowCount();
if (index < 0) {
index = max;
} else {
index++;
if (index > max) {
index = max;
}
}
addIndex = index;
String[] values = str.split("\n");
addCount = values.length;
int colCount = target.getColumnCount();
for (int ndx = 0; ndx < values.length; ndx++) {
model.insertRow(index++, values[ndx].split(","));
}
//If we are moving items around in the same table, we
//need to adjust the rows accordingly, since those
//after the insertion point have moved.
if (rows != null && addCount > 0) {
for (int ndx = 0; ndx < rows.length; ndx++) {
if (rows[ndx] > addIndex) {
rows[ndx] += addCount;
}
}
}
}
protected void cleanup(JComponent c, boolean remove) {
JTable source = (JTable) c;
if (remove && rows != null) {
DefaultTableModel model =
(DefaultTableModel) source.getModel();
for (int ndx = rows.length - 1; ndx >= 0; ndx--) {
model.removeRow(rows[ndx]);
}
}
rows = null;
addCount = 0;
addIndex = -1;
}
}
class ViewportTransferHandler extends TransferHandler {
private JComponent getView(JComponent comp) {
JViewport viewport = (JViewport) comp;
return (JComponent) viewport.getView();
}
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
JComponent view = getView(comp);
return view.getTransferHandler().canImport(view, transferFlavors);
}
public void exportAsDrag(JComponent comp, InputEvent e, int action) {
JComponent view = getView(comp);
view.getTransferHandler().exportAsDrag(view, e, action);
}
public void exportToClipboard(JComponent comp, Clipboard clip, int action) {
JComponent view = getView(comp);
view.getTransferHandler().exportToClipboard(view, clip, action);
}
public int getSourceActions(JComponent c) {
JComponent view = getView(c);
return view.getTransferHandler().getSourceActions(view);
}
public boolean importData(JComponent comp, Transferable t) {
JComponent view = getView(comp);
return view.getTransferHandler().importData(view, t);
}
}
}
Monday, June 7, 2010
Java and Swing Tips
How to check File exists or not?
File f = new File("Path name of the file");
if(f.exists())
{
System.out.println("File Exists");
}
How to create new Folder?
File newFolder = new File("Path name of the Folder");
nf.mkdir(newFolder);
How to popup Dialog screen center?
JDialog dg = new JDialog(null);
dg.setLocationRelativeTo(null);
// Dialog will popup on frame center
JFrame f = new JFrame("Owner");
JDialog dg = new JDialog(f);
dg.setLocationRelativeTo(f);
(or)
// centers the dialog within the screen [1.1]
// (put that in the Frame/Dialog class)
public void centerScreen() {
Dimension dim = getToolkit().getScreenSize();
Rectangle abounds = getBounds();
setLocation((dim.width - abounds.width) / 2,
(dim.height - abounds.height) / 2);
super.setVsible(true);
requestFocus();
}
// centers the dialog within the parent container [1.1]
// (put that in the Dialog class)
public void centerParent () {
int x;
int y;
// Find out our parent
Container myParent = getParent();
Point topLeft = myParent.getLocationOnScreen();
Dimension parentSize = myParent.getSize();
Dimension mySize = getSize();
if (parentSize.width > mySize.width)
x = ((parentSize.width - mySize.width)/2) + topLeft.x;
else
x = topLeft.x;
if (parentSize.height > mySize.height)
y = ((parentSize.height - mySize.height)/2) + topLeft.y;
else
y = topLeft.y;
setLocation (x, y);
super.setVsible(true);
requestFocus();
}
How to check filename consists of any special character using ascii values?
private boolean isValidFilename(String filename) {
char beginchar = filename.toCharArray()[0];
int aV = beginchar;
if (!((aV > 64 && aV <> 96 && aV < j =" 0;" fchar =" cArrforfile[j];" av =" fChar;"> 64 && aV <> 96 && aV <> 47 && aV < 59)|| (aV == 95))) {
System.out.println("Filename must not contain any special character");
return false;
}
}
return true;
}
Monday, March 15, 2010
Casting for Primitives
Casting | int |
---|---|
float | float f = 6.1; int i = (int)f; |
double | double d = 25.0; int i = (int)d; |
long | long l = 25.0; int i = (int)l; |
String | String str = "25"; int i = Integer.valueOf(str).intValue(); or int i = Integer.parseInt(str); |
Casting | float |
---|---|
int | int i = 6; float f= (float)i; |
double | double d = 25.0; float f = (float)d; |
long | long l = 25.0; float f = (float)l; |
String | float f = Float.valueOf(str).floatValue(); |
Casting | double |
---|---|
int | int i = 6; double d =(double)i; |
float | float f = 6.1; double d =(double)f; |
long | long l = 25.0; double d = (double)l; |
String | double d = Double.valueOf(str).doubleValue();
|
Casting | long |
---|---|
int | int i = 6; long l = (long)i; |
float | float f = 6.1; long l = (long)f; |
double | double d =25.0; long l= (long)d; |
String | long l = Long.valueOf(str).longValue(); or Long l = Long.parseLong(str); |
Casting | String |
---|---|
int | int i = 42; String str = Integer.toString(i); or String str = "" + i; |
float | String str = Float.toString(f); |
double | String str = Double.toString(i); |
long | String str = Long.toString(l); |
Example Programs : Overloading and overriding
class OverLoading
{
// Area for square
public double area(int a)
{
double sArea = a*a;
return sArea;
}
// Area for circle
public double area(double a)
{
double cArea = 3.14*a*a;
return cArea;
}
// Area for rectangle
public double area(double b, double h)
{
double rArea = b*h;
return rArea;
}
// Area for Eclipse
public double area(double b, int h)
{
double eArea = 0.5*b*h;
return eArea;
}
public static void main(String[] arg)
{
OverLoading oL = new OverLoading();
System.out.println(" Area for Square = "+oL.area(10));
System.out.println(" Area for Circle = "+oL.area(10.0));
System.out.println(" Area for Rectangle = "+oL.area(10.0,10.0));
System.out.println(" Area for Eclipse = "+oL.area(10.0,10));
}
}
2. Example for Overriding :
public class Overriding
{
public static void main(String arg[])
{
System.out.println(" ----------------------------------------");
System.out.println(" Animal a = new Animal(); ");
Animal a = new Animal();
System.out.println(" (non static mtd) a.eat() ");
a.eat();
System.out.println(" ( static mtd) a.showActualClassName() ");
a.showActualClassName();
System.out.println(" ----------------------------------------");
System.out.println(" ----------------------------------------");
System.out.println(" Tiger t = new Tiger(); ");
Tiger t = new Tiger();
System.out.println(" (non static mtd) t.eat() ");
t.eat();
System.out.println(" (static mtd) t.showActualClassName() ");
t.showActualClassName();
System.out.println(" ----------------------------------------");
System.out.println(" ----------------------------------------");
System.out.println(" Animal at = new Tiger(); ");
Animal at = new Tiger();
System.out.println(" (non static mtd) at.eat() ");
at.eat();
System.out.println(" ( static mtd) at.showActualClassName() ");
at.showActualClassName();
System.out.println(" ----------------------------------------");
}
}
class Animal
{
public Animal()
{
System.out.println("Animal constructor invoked");
}
public void eat()
{
System.out.println("Animal eat method called");
}
public static void showActualClassName()
{
System.out.println("This class name is : Animal");
}
}
class Tiger extends Animal
{
public Tiger()
{
System.out.println("Tiger constructor invoked");
}
public void eat()
{
System.out.println("Tiger eat method called");
}
public static void showActualClassName()
{
System.out.println("This class name is : Tiger");
}
}
Monday, February 22, 2010
Short Notes on Java Archive(JAR) file
JAR:
The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications
Advantages:
Security, A jar file can be digitally signed enabling users to verify the signature and then grant the program security privileges.
-
Decreased download time, since the archive is compressed it takes less time to download than it would to download each individual file.
Package Versioning, A Jar file may contain vendor and version information about the files it contains.
Portability, all Java Runtime Environments know how to handle Jar files.
Example:
Making javafile and compile that
package amir;
public class Hello
{
public static void main(String arg[])
{
System.out.println("Hello its form Hello.java inside amir package");
}
}
javac Hello.java
then amir directory have amir->Hello.java
->Hello.class
-
Creating mainclass file:
mainclass contains below line
Main-Class: amir.Hello -
Making jar files:
jar cmf mainclass myfirst.jar amir/Hello.class
then u will get myfirst.jar -
Viewing jar files:
jar tf myfirst.jar
then it will show as below
META-INF/
META-INF/MANIFEST.MF
amir/Hello.class -
Running jar file:
java -jar myfirst.jar
output:
Hello its form Hello.java inside amir package