Labels
|
|
Friday, 5 July 2013
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);
}
});
}
}
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.
|
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.
|
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:
|
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();
}
}
}
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();
}
}
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.
|
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.
|
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
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.
|
There are some rules that need to be followed when we want to implement a singleton.
- from the example code above you can see that a singleton has a static variable to keep it sole instance.
- 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.
- 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().
- 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.
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.
|
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
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();
}
}
}
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.
|
Here is the different result of the code above.
1.0055000075E8
100550000.75
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.
|
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
How do I use StringTokenizer to split a string?
|
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
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.
|
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.
|
Our sample code result is shown below:
Java
Sample
Code
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:
|
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
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.
|
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
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.
|
The result of our code is:
Happy
New
Year
2006
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.
|
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 |