Friday, June 11, 2010

DragandDrop in JTable

TransferHandler is used to handle the transfer of a Transferable to and from Swing components. The Transferable is used to represent data that is exchanged via a cut, copy, or paste to/from a clipboard. It is also used in drag-and-drop operations to represent a drag from a component, and a drop to a component. Swing provides functionality that automatically supports cut, copy, and paste keyboard bindings that use the functionality provided by an implementation of this class. Swing also provides functionality that automatically supports drag and drop that uses the functionality provided by an implementation of this class. The Swing developer can concentrate on specifying the semantics of a transfer primarily by setting the transferHandler property on a Swing component.

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

1. Example for Overloading :

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:

  1. 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

  1. Creating mainclass file:
    mainclass contains below line
    Main-Class: amir.Hello

  2. Making jar files:
    jar cmf mainclass myfirst.jar amir/Hello.class
    then u will get myfirst.jar

  3. Viewing jar files:
    jar tf myfirst.jar
    then it will show as below
    META-INF/
    META-INF/MANIFEST.MF
    amir/Hello.class

  4. Running jar file:
    java -jar myfirst.jar
    output:
    Hello its form Hello.java inside amir package

Monday, February 15, 2010

Java Basics-1

Class(Logical construct):
Template or Blueprint of an object.
or
Structure and Behaviour of an object.

Object(Physical reality):
Instance of a class .

Overloading:
Same method name and method signature to be vary.
Method signature -> number of arguements
-> order of arguements
-> diff data types
Overriding:
Method name and signature to be same.

abstract class:
It is a class that cannot instantiate. It can be extended or subclassed. It may or may not contain abstarct method. abstract method is a method to have only method definition not implementation(its ends with semi-colen without curly brackets). It is used to single inheritance.

interface:
It is a refernce type similar to a class. It contains common methods and constants to a group of classes.
All interface to be pure abstract. It is used to multiple inheritance.

final:
In front of variable - to be constant.
In front of method - cannot override.
In front of class - cannot inherit.

public -> can acess within class / same package / other package.
private->can acess within class.
protected-> can acces within class / same package / parent-child relationship.
default-> can acces within class / same package .

Thursday, February 11, 2010

Short notes on Thread

Thread:

A Thread is a path of execution of a program. A thread is a sequence of instructions that executed in a define unique flow of control.

SingleThread: A process is made up of one thread.

MultiThread: A process is made up of two or more thread.

Multitasking: It is a ability to do two or more tasks at a same time.


Create a Thread

-> extends Thread class
-> implements Runnable interface (its to be more useful because in big projects super class to be reserved one)

Process based:

It enables a computer to create more process concurrently. Each process having separate memory address location. So switches from one process to another , processor have face more overloads.

Thread based:

A program cotains more threads , it can do more tasks simultaneusly.

A processor switches from one thread to another with fewer overloads. It is also called as Light process.

Advantage:

  1. Improved performance

  2. Minimized system resource usage.

  3. Simultaneusly to use multiple application.

  4. Program structure simplification.

DisAdvantage:

Race condition: When two or more threads try to access the same variable atleast one thread should to write that variable before to access. Its arised because of lack of synchronization.

DeadLock: When two threads are waiting for each other for complete their operation before complete their individual actions.

Lock-starvation: While execution of thread postponed because of that low priority. Java runtime environment executes the thread based on priority. Because CPU executes one thread at a time. Thread priority value 1-10.

Life Cycle:

1.New: While thread initialized it will enter to init state. After we should call start() method, Otherwise it will cause IllegalThreadStateException.

2.Runnable: Once start method called then it will enter to runnable state. Start method allocate each thread resource and sheduldes it ,then it will call run() method.

3.NotRunnable: 3 ways

-> sleep() - wait for specified time.

-> wait() - wait until notify.

-> Blocked by another thread – Blocked thread while I/O opeartion.

4.Dead: if run method completed or thread object to be asign to null then its enter to this state.

Synchronization: Used to avoid racecondition or deadLock effects . Synchronization means serializing the threads. It allows to execute one thread at a time.