Archive

Posts Tagged ‘Java’

JAVA – Hot To Rename a File or Directory.

A quick script to re-name a file or folder:

Import required:

import java.io.File;

Code:

try{       
        // File name (or directory) of the file to be renamed
        File file = new File(“c:/file1.txt”);
        // New File name (or directory)
        File file2 = new File(“c:/file2.txt”);
        // Rename file (or directory)
        file.renameTo(file2);
    }catch(Exception e){
        e.printStackTrace();
    }

Categories: Java Tags: , , , , ,

JAVA – How To Convert Integer (INT) To Hexidecimal (HEX)

Integer to Hexidecimal string:

int intVal = 123;
String hexVal = Integer.toHexString(intVal);
System.out.println(“Hexidecimal: ” + hexVal);

Output:

Hexidecimal: 7b

Hexidecimal string to Integer:

String hexVal = “7b”;
int intVal = Integer.parseInt(hexVal,16);
System.out.println(“Integer: ” + intVal);Output:

Output:

Integer: 123

Categories: Java Tags: , , , , ,

JAVA – How To Get The Current Directory

The following script gets the current directory at runtime:

import java.io.File;

public class CurrentDir {
   public static void main (String args[]) {
     File dir = new File (“.”);
     try {
       System.out.println (“Current Directory : ” + dir.getCanonicalPath());       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}

The same logic can be used to get the parent to the current directory:

import java.io.File;

public class ParentDir {
   public static void main (String args[]) {
     File dir = new File (“..”);
     try {
       System.out.println (“Parent  Directory : ” + dir.getCanonicalPath());
       }
     catch(Exception e) {
       e.printStackTrace();
       }
     }
}

JAVA – How To Calculate An Age From A Date Of Birth (DOB)

June 15, 2009 8 comments

The following code illustrates how to derive an age from a given DOB.

This example uses the DOB format YYYY-MM-DD.

This can be altered to any format by changing the substrings taken from the original DOB input.

String dob = “1984-09-20″;

//TAKE SUBSTRINGS OF THE DOB SO SPLIT OUT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
int yearDOB = Integer.parseInt(dob.substring(0, 4));
int monthDOB = Integer.parseInt(dob.substring(5, 7));
int dayDOB = Integer.parseInt(dob.substring(8, 10));

//CALCULATE THE CURRENT YEAR, MONTH AND DAY
//INTO SEPERATE VARIABLES
DateFormat dateFormat = new SimpleDateFormat(“yyyy”);
java.util.Date date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));

dateFormat = new SimpleDateFormat(“MM”);
date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));

dateFormat = new SimpleDateFormat(“dd”);
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));

//CREATE AN AGE VARIABLE TO HOLD THE CALCULATED AGE
//TO START WILL – SET THE AGE EQUEL TO THE CURRENT YEAR MINUS THE YEAR
//OF THE DOB
int age = thisYear – yearDOB;

//IF THE CURRENT MONTH IS LESS THAN THE DOB MONTH
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth < monthDOB){
age = age – 1;
}

//IF THE MONTH IN THE DOB IS EQUEL TO THE CURRENT MONTH
//THEN CHECK THE DAY TO FIND OUT IF THEY HAVE HAD THEIR
//BIRTHDAY YET. IF THE CURRENT DAY IS LESS THAN THE DAY OF THE DOB
//THEN REDUCE THE DOB BY 1 AS THEY HAVE NOT HAD THEIR
//BIRTHDAY YET THIS YEAR
if(thisMonth == monthDOB && thisDay < dayDOB){
age = age – 1;
}

//THE AGE VARIBALE WILL NOW CONTAIN THE CORRECT AGE
//DERIVED FROMTHE GIVEN DOB
System.out.println(age);



This process calculates the current year, month and date to work out if the DOB has already passed this year in order to accuratly establish the age.

Categories: Java Tags: , , ,

Java – Random Number Generator / How To Generate A Random Number

This is a simple method for generating a random number between zero (0) and a given number.

The following code example with generate a random number between 0 and 49.

Although the value of maxNumber is set to 50, Java will start the count at 0.

If you want a number between 0 and 50, set the value of maxNymber to 51.

int maxNumber = 50;
int randomNumber = (int)Math.floor(Math.random() * maxNumber);


JAVA – Set The Position Of The ScrollBar In JScrollPane()



The following codes assumes that you have created a JScrollPane() called scrollPane


int x = 0;
int y = 10;

scrollPane.getViewport().setViewPosition(new java.awt.Point(x, y));





In this example x sets the horizontal position of a horizontal scroll bar.
y sets the vertical position of a vertical scroll bar – in this case the vertical scroll bar will appear 10 pixels down from the top.

Categories: Java Tags: , , , , ,

JAVA – Remove Row from A JTable

March 30, 2009 2 comments

How to remeve a row from a JTable.

This example illustrates how to remove a row from an existing JTable called table.
The row to be deleted will be the row that has been selected by clicking the mouse on it.

 

//CREATE MODEL INSTANCE FROM EXISTING TABLE
DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel) table.getModel();

//DELETE THE SELECTED ROW
model.removeRow(table.getSelectedRow());
                
//INSERT A NEW EMPTY ROW
model.addRow(new Object[]{“”,”",”"});

 

I used this with a confimation dialog, asking the user to confirm this is the correct row to be deleted;

int n = JOptionPane.showConfirmDialog(

null,

                “Are you sure you want delete – ” + table.getValueAt(table.getSelectedRow(), 2) + “?”,

                “”,

                JOptionPane.YES_NO_CANCEL_OPTION);          

           

//the user has clicked the cross

if(n == -1)

{

   return;

}

           

//the user has clicked cancel

if(n == 2)

{

   return;

}

 

//yes

if(n == 0){

   

    //CREATE MODEL INSTANCE FROM EXISTING TABLE

    DefaultTableModel model = new DefaultTableModel();

    model = (DefaultTableModel) table.getModel();

 

    //DELETE THE SELECTED ROW

    model.removeRow(table.getSelectedRow());

               

    //INSERT A NEW EMPTY ROW

    model.addRow(new Object[]{“”,”",”"});

}

           

//no

if(n == 1){

    return;

}

Categories: Java Tags: , , ,

JAVA Check For A Valid Email Address String

February 12, 2009 6 comments

How to check for a valid email address string.

Example Code:

String email = “test@test.com”;
Pattern p = Pattern.compile(“.+@.+\\.[a-z]+”);
Matcher m = p.matcher(email);
boolean matchFound = m.matches();

if(matchFound){
System.out.println(“EMAIL OK”);
}else{
System.out.println(“EMAIL ERROR”);
}

Categories: Java Tags: , ,

Convert A String To Proper Case In Java

February 12, 2009 1 comment

Converting a string to proper case in Java.
e.g. convert “roBErT” to “Robert”.

Example code:

String forename = “roBErT”;
String forenameforenameInitial = “”;

forename = forename.toLowerCase();
forenameInitial = forename.substring(0, 1).toUpperCase();
forename = forenameInitial + forename.substring(1,forename.length());

System.out.println(forename);

The string vaiable forename now has a value of  “Robert”.

Categories: Java Tags: , ,

Launch Web Browser From Java Application

February 12, 2009 Leave a comment

Opening a web browser from a Java application.

Bare Bones Browser is a great tool for opening a web browser on a given URL from a Java / Swing application.

Step 1 – Firstly create an empty class called BareBonesBrowserLaunch.java.

Copy and paste the entire section of code below into the class:

/////////////////////////////////////////////////////////
//  Bare Bones Browser Launch                          //
//  Version 1.5 (December 10, 2005)                    //
//  By Dem Pilafian                                    //
//  Supports: Mac OS X, GNU/Linux, Unix, Windows XP    //
//  Example Usage:                                     //
//     String url = “http://www.centerkey.com/”;       //
//     BareBonesBrowserLaunch.openURL(url);            //
//  Public Domain Software — Free to Use as You Like  //
/////////////////////////////////////////////////////////

import java.lang.reflect.Method;
import javax.swing.JOptionPane;

public class BareBonesBrowserLaunch {

private static final String errMsg = “Error attempting to launch web browser”;

public static void openURL(String url) {
String osName = System.getProperty(“os.name”);
try {
if (osName.startsWith(“Mac OS”)) {
Class fileMgr = Class.forName(“com.apple.eio.FileManager”);
Method openURL = fileMgr.getDeclaredMethod(“openURL”,
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith(“Windows”))
Runtime.getRuntime().exec(“rundll32 url.dll,FileProtocolHandler ” + url);
else { //assume Unix or Linux
String[] browsers = {
“firefox”, “opera”, “konqueror”, “epiphany”, “mozilla”, “netscape” };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] {“which”, browsers[count]}).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception(“Could not find web browser”);
else
Runtime.getRuntime().exec(new String[] {browser, url});
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + “:\n” + e.getLocalizedMessage());
}
}

}

Step 2 – To open the web browser from an application, you need to call the  BareBonesBrowserLaunch.openURL() method.

The following example shows the basic call:

String URL = “www.google.co.uk”;
BareBonesBrowserLaunch.openURL(URL);

Categories: Java Tags: , ,
Follow

Get every new post delivered to your Inbox.