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;
}

No comments:

Post a Comment