Showing posts with label JAVA Code Examples. Show all posts
Showing posts with label JAVA Code Examples. Show all posts

How do I set the look and feel for swing application?


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LookAndFeelDemo extends JFrame {
public LookAndFeelDemo() {
initComponents();
}

public void initComponents() {
setSize(200, 200);
setTitle("LAF Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));

JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Look and Feel");

final JFrame frame = this;

//
// Get all the available look and feel that we are going to use for
// creating the JMenuItem and assign the action listener to handle
// the selection of menu item to change the look and feel.
//
UIManager.LookAndFeelInfo[] lookAndFeelInfos = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < lookAndFeelInfos.length; i++) {
final UIManager.LookAndFeelInfo lookAndFeelInfo = lookAndFeelInfos[i];
JMenuItem item = new JMenuItem(lookAndFeelInfo.getName());
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//
// Set the look and feel for the frame and update the UI
// to use a new selected look and feel.
//
UIManager.setLookAndFeel(lookAndFeelInfo.getClassName());
SwingUtilities.updateComponentTreeUI(frame);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
}
});
menu.add(item);
}

menuBar.add(menu);

getContentPane().add(menuBar);
getContentPane().add(new JButton("Hello"));
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LookAndFeelDemo().setVisible(true);
}
});
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I make a centered JFrame?


If you have a JFrame and you want to center the position in the screen you can use the following formula. Let's say you have a class called MainForm.



import java.awt.*;
import javax.swing.*;

public class MainForm extends JFrame
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Get the size of our screen
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();

MainForm mainForm = new MainForm();
mainForm.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);

mainForm.setSize(250, 250);

// Calculates the position where the MainForm
// should be paced on the screen.
mainForm.setLocation((screenSize.width -
mainForm.getWidth()) / 2,
(screenSize.height -
mainForm.getHeight()) / 2);

mainForm.pack();
mainForm.setVisible(true);
}
});
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I create a connection to database?


An example for obtaining a connection to MySQL database. For connecting to other database all you have to do is change the url to match to url format for a particular database and of course you have to register a correct JDBC driver of the database you are using.



import java.sql.DriverManager;
import java.sql.Connection;

public class ConnectionSample
{
// Below is the format of jdbc url for MySql database.
public static final String URL =
"jdbc:mysql://localhost/testdb";

// The username for connecting to the database
public static final String USERNAME = "root";

// The password for connecting to the database
public static final String PASSWORD = "";

public static void main(String[] args) throws Exception
{
Connection connection = null;
try
{
// Register a database jdbc driver to be used by
// our program. In this example I choose a MySQL
// driver.
Class.forName("com.mysql.jdbc.Driver");

// Get the connection object from the driver manager
// by passing the url of our database, username and
// the password.
connection = DriverManager.getConnection(URL,
USERNAME, PASSWORD);

// Do what ever you want to do with the connection
// object, such as reading some records from database,
// updating or deleting a row. But don't for get the
// close the connection right after you've finished
// using it.
} finally
{
if (connection != null)
{
connection.close();
}
}
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

What is Autoboxing?


Autoboxing is a new feature offered in the Tiger (1.5) release of Java SDK. In sort auto boxing is a capability to convert or cast between object wrapper and it's primitive type.

Previously when placing a primitive data into one of the Java Collection Framework we have to wrap it to an object because the collection cannot work with primitive data. Also when calling a method that requires an instance of object than an int or long, than we have to convert it too.

But now, starting from version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explisit object casting.

Here an example how it will look like using the Autoboxing feature:


public static void main(String[] args)
{
Map map = new HashMap();

// Here we put an int into the Map, and it accepted
// as it will be autoboxed or converted into the wrapper
// of this type, in this case the Integer object.
map.put("Age", 25);

// Here we can just get the value from the map, no need
// to cast it from Integer to int.
int age = map.get("Age");

// Here we simply do the math on the primitive type
// and got the result as an Integer.
Integer newAge = age + 10;
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I create a zip file?


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingFileExample {
public static void main(String[] args) {
try {
String source = "text.txt";
String target = "example.zip";

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));
FileInputStream fis = new FileInputStream(source);

// put a new ZipEntry in the ZipOutputStream
zos.putNextEntry(new ZipEntry(source));

int size = 0;
byte[] buffer = new byte[1024];

// read data to the end of the source file and write it to the zip
// output stream.
while ((size = fis.read(buffer)) > 0) {
zos.write(buffer);
}

zos.closeEntry();
fis.close();

// Finish zip process
zos.close();


} catch (IOException e) {
e.printStackTrace();
}
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I create a beep sound?



import java.awt.*;

public class BeepExample {
public static void main(String[] args) {
// This is the way we can send a beep audio out.
Toolkit.getDefaultToolkit().beep();
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I split a string?


String class introduce a String.split(String regex) method that simplify this process.

Below is a code sample how to do it.



public class StringSplit
{
public static void main(String[] args)
{
String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
System.out.println("item = " + item);
}
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I reverse a string?


Below is an example code that reverse a string. Here we use a StringBuffer.reverse() method to reverse a string. In a 1.5 version a new class called StringBuilder also has a reverse() method that do just the same, one of the difference is StringBuffer class is synchronized while StringBuilder class does not.

Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order. So here is the string reverse in the StringBuffer way.




public class StringReverseExample
{
public static void main(String[] args)
{
// The normal sentence that is going to be reversed.
String words = "Morning of The World - The Last Paradise on Earth";

// To reverse the string we can use the reverse() method in the
// StringBuffer class. The reverse() method returns a StringBuffer so
// we need to call the toString() method to get a string object.
String reverse = new StringBuffer(words).reverse().toString();

// Print the normal string
System.out.println("Normal : " + words);
// Print the string in reversed order
System.out.println("Reverse: " + reverse);
}
}

And below is the result.

Normal : Morning of The World - The Last Paradise on Earth
Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I implement a Singleton pattern?


Singleton pattern used when we want to allow only a single instance of a class can be created inside our application. Using this pattern ensures that a class only have a single instance by protecting the class creation process, by setting the class constructor into private access modifier.

To get the class instance, the singleton class can provide a method for example a getInstance() method, this will be the only method that can be accessed to get the instance.


public class SingletonPattern
{
private static SingletonPattern instance;

private SingletonPattern()
{
}

public static synchronized SingletonPattern getInstance()
{
if (instance == null)
{
instance = new SingletonPattern();
}
return instance;
}
}

There are some rules that need to be followed when we want to implement a singleton.

  1. from the example code above you can see that a singleton has a static variable to keep it sole instance.
  2. you need to set the class constructor into private access modifier. By this you will not allowed any other class to create an instance of this singleton because they have no access to the constructor.
  3. because no other class can instantiate this singleton how can we use it? the answer is the singleton should provide a service to it users by providing some method that returns the instance, for example getInstance().
  4. when we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

Hello World example in Java


Hello World is a classic sample to start when we learn a new programming language. Below is the Java version of Hello World program, it simple enough to start.


public class HelloWorld
{
public static void main(String[] args)
{
// say hello to the world
System.out.println("Hello World!");
}
}

The code contains one class called HelloWorld, a main(String[] args) method which is the execution entry point of every Java application and a single line of code that write a Hello World string to the console. That's all, we are done!

To run the application we need to compile it first. I assume that you have your Java in your path. To compile it type

% javac HelloWorld.java

The compilation process will result a file called HelloWorld.class, this is the binary version of our program. As you can see that the file ends with .class extension because Java is everyting about class.

To run it type the command bellow, class name is written without it extension.

% java HelloWorld


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I write string data to file?


import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class WriteToFileExample
{
public static void main(String[] args)
{
try
{
// Here we'll write our data into a file called
// sample.txt, this is the output.
File file = new File("sample.txt");
// We'll write the string below into the file
String data = "Learning Java Programming";

// To write a file called the writeStringToFile
// method which require you to pass the file and
// the data to be written.
FileUtils.writeStringToFile(file, data);
} catch (IOException e)
{
e.printStackTrace();
}
}
}



Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I format a number?


If you want to display some numbers that is formatted to a certain pattern, either in a Java Swing application or in a JSP file, you can utilize NumberFormat and DecimalFormat class to give you the format that you want. Here is a small example that will show you how to do it.



import java.text.DecimalFormat;
import java.text.NumberFormat;

public class DecimalFormatExample
{
public static void main(String[] args)
{
// We have some millons money here that we'll format its look.
double money = 100550000.75;

// By default to toString() method of the Double data type will print
// the money value using a scientific number format as it is greater
// than 10^7 (10,000,000.00). To be able to display the number without
// scientific number format we can use java.text.DecimalFormat wich
// is a sub class of java.text.NumberFormat.

// Below we create a formatter with a pattern of #0.00. The # symbol
// means any number but leading zero will not be displayed. The 0
// symbol will display the remaining digit and will display as zero
// if no digit is available.
NumberFormat formatter = new DecimalFormat("#0.00");

// Print the number using scientific number format.
System.out.println(money);

// Print the number using our defined decimal format pattern as above.
System.out.println(formatter.format(money));
}
}

Here is the different result of the code above.

1.0055000075E8
100550000.75


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I do a date add or substract?


The java.util.Calendar allows us to do a date arithmetic function such as add or substract a unit of time to the specified date field.

The method that done this process is the Calendar.add(int field, int amount). Where the value of the field can be Calendar.DATE, Calendar.MONTH, Calendar.YEAR. So this mean if you want to substract in days, months or years use Calendar.DATE, Calendar.MONTH or Calendar.YEAR respectively.


import java.util.Calendar;

public class CalendarAddExample
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();

System.out.println("Today : " + cal.getTime());

// Substract 30 days from the calendar
cal.add(Calendar.DATE, -30);
System.out.println("30 days ago: " + cal.getTime());

// Add 10 months to the calendar
cal.add(Calendar.MONTH, 10);
System.out.println("10 months later: " + cal.getTime());

// Substract 1 year from the calendar
cal.add(Calendar.YEAR, -1)
System.out.println("1 year ago: " + cal.getTime());
}
}

In the code above we want to know what is the date back to 30 days ago.

The sample result of the code is shown below:

Today : Tue Jan 03 06:53:03 ICT 2006
30 days ago: Sun Dec 04 06:53:03 ICT 2005


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I use StringTokenizer to split a string?



import java.util.StringTokenizer;

public class StringTokenizerSample
{
public static void main(String[] args)
{
StringTokenizer st =
new StringTokenizer("a stringtokenizer sample");

// get how many tokens inside st object
System.out.println("tokens count: " + st.countTokens());

// iterate st object to get more tokens from it
while (st.hasMoreElements())
{
String token = st.nextElement().toString();
System.out.println("token = " + token);
}

// split a date string using a forward slash as
// delimiter
st = new StringTokenizer("2005/12/15", "/");
while (st.hasMoreElements())
{
String token = st.nextToken();
System.out.println("token = " + token);
}
}
}

The above code is an example of using StringTokenizer to split a string. In the current JDK this class is discourageg to be used, using instead the String.split(...) method or using a new java.util.regex package.

Here is the result of this sample code:

tokens count: 3
token = a
token = stringtokenizer
token = sample
token = 2005
token = 12
token = 15


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I read a text file?


The code shown below is an example how to read a text file. This program will read a file called test.txt and shown its content.


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTextFileExample
{
public static void main(String[] args)
{
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;

try
{
reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((text = reader.readLine()) != null)
{
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (reader != null)
{
reader.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}

// show file contents here
System.out.println(contents.toString());
}
}


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I convert collection into array?


To convert collection-based data into array we can use toArray() method provided by the implementation of Collection interface such as java.util.ArrayList.


import java.util.List;
import java.util.ArrayList;

public class CollectionToArrayExample
{
public static void main(String[] args)
{
List list = new ArrayList();
list.add("Java");
list.add("Sample");
list.add("Code");

Object[] array = list.toArray();
for (int i = 0; i < style="color: rgb(0, 102, 0);">length; i++)
{
System.out.println(array[i].toString());
}
}
}

Our sample code result is shown below:


Java
Sample
Code


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I get the current month name?


To get the current month name from the system we can use java.util.Calendar class. The Calendar.get(Calendar.MONTH) returns the month value as an integer starting from 0 as the first month and 11 as the last month. This mean January equals to 0, February equals to 1 and December equals to 11.

Let's see the code below:


import java.util.Calendar;

public class GetMonthNameExample
{
public static void main(String[] args)
{
String[] monthName = {"January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October", "November",
"December"};

Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];

System.out.println("Month name: " + month);
}
}

On the first line inside the main method we declare an array of string that keep our month names. Next we get the integer value of the current month and at the last step we look for the month name inside our previously defined array.

The example result of this program is:

Month name: January


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I get day, month, year value from the current date?


What day, month, year, day of week, day of month, day of year is today? If we want to answer these question we can use java.util.Calendar and java.util.GregorianCalendar which is the implementation of Calendar abstract class.

These classes can help us to get integer value such as day, month, year from a Date object. Let's see the example code.


import java.util.Calendar;

public class CalendarExample
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
int dow = cal.get(Calendar.DAY_OF_WEEK);
int dom = cal.get(Calendar.DAY_OF_MONTH);
int doy = cal.get(Calendar.DAY_OF_YEAR);

System.out.println("Current Date: " + cal.getTime());
System.out.println("Day: " + day);
System.out.println("Month: " + month);
System.out.println("Year: " + year);
System.out.println("Day of Week: " + dow);
System.out.println("Day of Month: " + dom);
System.out.println("Day of Year: " + doy);
}
}

Here is the result of this example:

Current Date: Thu Dec 29 13:41:09 ICT 2005
Day: 29
Month: 12
Year: 2005
Day of Week: 5
Day of Month: 29
Day of Year: 363


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I convert array to collection?


To convert array based data into list / collection based we can use java.util.Arrays class. This class provide a static method asList(Object[] a) that converts array into list / collection.


import java.util.Arrays;
import java.util.List;
import java.util.Iterator;

public class ArraysExample
{
public static void main(String[] args)
{
String[] array = {"Happy", "New", "Year", "2006"};
List list = Arrays.asList(array);

Iterator iterator = list.iterator();
while (iterator.hasNext())
{
System.out.println((String) iterator.next());
}
}
}

The result of our code is:

Happy
New
Year
2006


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

How do I convert String to Date object?


The following code shows how we can convert a string representation of date into java.util.Date object.

To convert a string of date we can use the help from java.text.SimpleDateFormat that extends java.text.DateFormat abstract class.



import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class StringToDate
{
public static void main(String[] args)
{
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

try
{
Date today = df.parse("20/12/2005");
System.out.println("Today = " + df.format(today));
} catch (ParseException e)
{
e.printStackTrace();
}
}
}

And here is the result of our code:

Today = 20/12/2005

The example starts by creating an instance of SimpleDateFormat with "dd/MM/yyyy" format which mean that the date string is formatted in day-month-year sequence.

Finally using the parse(String source) method we can get the Date instance. Because parse method can throw java.text.ParseException exception if the supplied date is not in a valid format; we need to catch it.

Here are the list of defined patterns that can be used to format the date taken from the Java class documentation.

Letter Date / Time Component Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800


Click Here to See Answer .....
Did you like this article ?
Subscribe to my RSS feed and get more JAVA Question, and Guideline, Plus a lot more great advice to help your Software Career.

Related JAVA Questions Posts