About these ads

Answer to Viktor Wijaya’s Question About String Class

12 10 2009

On Thursday, October 8th 2009, I was teaching basic programming lab for the 1st semester students in Swiss German University and the topic to be covered are from JAVA Concepts book chapter 1-4. When, we were discussing about the String class, a student named Viktor Wijaya asked me :

Viktor: “I was wondering why we can do String text = “some text”? Don’t we have to instantiate every object by using a new keyword like MyClass a = new MyClass()”.

To be honest, I didn’t expect that question at all and I realized that after years of using JAVA that String class doesn’t have to be instantiated by a new keyword. I got to say that’s an excellent question and I got no answer to that in the meantime. My curiosity went through and I searched for the answer of the question launched by Viktor. After a while searching in the internet, I found the answer to the 1 million dollars question. So Viktor, here’s the answer to my understanding:

String is a rare class in Java. It’s allowed to straddle the line between behaving as an object (using new() ) and behaving as a primitive (using direct assignment). The designers knew String objects would be prominent in almost any program. To conserve the run-time cost of creating them, they chose to allow static String assignments. Static assignments are “paid for” at compilation time, where they can be less of a burden.

Another difference on the declaration is on the object creation. String class is an immutable class, so once you declare it, it can’t be changed. You might think it changed but actually the system creates a new object and move the pointer of the variable to the new object.

Now, about the instantiation. If you use the new() keyword, the system will create a new object every time the new() keyword is invoked. So if you declare a String as String text = new String(data), where data is an array of characters, the system will create a new object when the instantiation is invoked. Because of this behaviour, instantiating two similar string over two different variables will yield different objects. Or in other words:

char[] data = {‘a’,'b’,'c’};

String text1 = new String(data);

String text2 = new String(data);

text1 == text2 ? ==> will yield a false result since the objects are different.

However, using direct assignment for the instantiation of String will yield a different process. When we do, String text = “a text”, it will create a new object to be pointed to the “text” reference. When we instantiated another string variable using direct assignement, the system will search for the specified string that has been instantiated previously. If it found a matching string, the system will use that object. If not, it will create a new object. Or in other words:

String text1 = “abc”;

String text2 = “abc”;

text1 == text2? ==> will yield a true result since “abc” has been instantiated in “text1″ variable.

So, there you go Victor. The answer to why a String class can be instantiated using direct assignment. I hope you understand the explanation I gave to you. If not, we’ll discuss it in the class. Cheers!

About these ads




Oct 2009: Answer to Basic Programming 1st Quiz

11 10 2009

On Friday, October 9th 2009, the first quiz of basic programming was conducted by James Purnama. It was a 65 questions and 1 programming problem quiz. The topic covered in this quiz is from JAVA Concepts book chapter 1-4. The students can do an open book or search it in the web. Anyway, I thought I might share the quiz and the answer which I think is right to you guys for improving your programming knowledge. Use this answer at your own risk.

1. Consider the following statement:
String greeting = 13;
Which of the following is true?
Answer: B. The statement yields a compile-time error
Explanation: The assignment operator is mismatched since it
wants to store an integer to a string type reference.
Since this type of inconvertible error is detected during the
compile time, it will yield a compile-time error.

2. Which of the following statement is correct?
Answer: A. Identifiers can be made up of letters, digits, and
the underscore(_)characters.

3. List three rules imposed by Java on identifiers.
Answer: All true

4. It is an error to use the value of a variable that has never
had a value assigned to it.
Answer: A. True
Explanation: The compiler will say "The variable may not have
been initialized".

5. Which of the following code fragments will cause an error?
Answer:
D. int luckyNumber;
   System.out.println(luckyNumber);
Explanation: the variable "luckyNumber" was never initialized.

6. System.out is an object of the class .....
Answer: PrintStream

7. The ...... of a class specifies what you can do with its objects.
Answer: public interface

8. The System.out object belongs to the class.....
Answer: B. PrintStream

9. Which of the following statements is correct in the Java language?
Answer: C. Every object belongs to a class 

10. Which of the following counts the number of characters in a string?
String greeting = "Hello, World!";
Answer: A. int n = greeting.length();

11. Write a statement that sets the value of i to the number of characters
in the following string:
int i;
String message = "Go home early today.";
Answer: i = message.length();

12. A method name is ..... if a class has more than one method with that name
(but different parameter types).
Answer: overloading

13. In Java, numbers are objects of classes in the java.lang package.
Answer: B.False
Explanation: number is a primitive object which doesn't belong to a class.

14. Based on the code below, move the rectangle 25 units to the left and
40 units down.
Rectangle box = new Rectangle(5,10,20,30);
Answer: box.translate(-25,40);

15. An object can be referenced by at most one object variable.
Answer: B. False

16. Which of the following terms denotes the memory location of an object?
Answer: C. object reference

17. Object variables store .....
Answer: A. references

18. The acronym of AWT stands for ....
Answer: C. Abstract Windowing Toolkit

19. Complete this code fragment to ensure the frame is shown.
JFrame frame = new JFrame();
Answer: C. frame.setVisible(true);

20. Based on the code below, set the size of the frame to 50 pixels wide and
70 pixels tall.
JFrame frame = new JFrame();
Answer: frame.setSize(50,70);

21.Based on the following statement, which of the following statements sets the title
of the frame?
Answer: D. frame.setTitle("An Empty Frame");

22.Complete this code fragment to ensure that the application exits properly when the
user closes the frame.
JFrame frame = new JFrame();
Answer: D. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

23. Complete the following code fragment by writing two statements that would cause
a program to display a square frame with a title that reads "My first GUI program".
JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
Answer:
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("My first GUI program");

24. Place drawing instruction inside the ... method. That method is called whenever
the component needs to be repainted.
Answer: paintComponent

25. To draw an ellipse, you must include in your program the statement: import ...
Answer: java.awt.geom.Ellipse2D

26. The Graphics and Graphics2D class are part of the ... package.
Answer: AWT

27. When a window is shown the first time, the ... method is called automatically.
Answer: main

28. Use a(n) ... to recover the Graphics2D object from the Graphics parameter
of the paintComponent method.
Answer: Cast

29. Whenever the Swing toolkit calls the paintComponent method, it actually passes
a parameter of type ...
Answer: D. Graphics

30. ... is the nickname for the graphical user interface library in Java.
Answer: GUI

31. To run an applet, you need a(n) ... file with the applet tag.
Answer: HTML

32. You view applets with the ... or a Java enabled browser.
Answer: AppletViewer

33. Which of the following statements would complete the code below?
public class RectangleComponent extends JComponent
{ public void paintComponent(Graphics g)
  { //Recover Graphics2D
    Graphics2D g2 = (Graphics2D) g;
    //Draw a square
    ...
    g2.draw(box);
  }
}
Answer: A. Rectangle box = new Rectangle (5,10,20,20);

34. Consider the following code fragment:
public class RedFlagComponent
{

    public void paintComponent(Graphics g)
    {
          Graphics2D g2 = (Graphics2D) g;
          Rectangle flag = new Rectangle(100, 100, 200, 100);
          g2.draw(flag);
    } 

}
Answer: D. It is impossible to add a RedFlagComponent object to a frame because
the class does not extend JComponent.

35. Complete the code below:
public void paint(Graphics g)
{
  //prepare for extended graphics
  Graphics2D g2 = (Graphics 2D) g;

  //Construct a rectangle and draw it
  Rectangle box = new Rectangle(5,10,20,30);
  g2.draw(box);

  //Move the rectangle 15 units to the right and 25 units down
  ...
  g2.draw(box);
}
Answer: box.translate(15,25);

36. The ... method of the Graphics2D class is used to draw a string anywhere in a
component.
Answer: drawString

37. In Java, colors are specified by defining their ..., ..., and ... values.
Answer: Red, Blue, Green

38. To draw a line in Java, you should use an object of the .... class.
Answer: Line2D

39. What are the RGB color of Color.RED?
Answer: C. 255,0,0

40. What are the RGB color of Color.BLACK?
Answer: D. 0,0,0

41. In the code below, write a statement that sets the graphic to green.
public class ItalianFlagComponent extends JComponent
{
  public void paintComponent(Graphics g)
  {
     Graphics2D g2 = (Graphics2D) g;
     Rectangle.Double leftRectangle = new Rectangle.Double(100,100,30,60);
     ...
  }
}
Answer: B. g2.setColow(Color.GREEN);

42. Complete the following statement, which construct an ellipse.
Ellipse2D.Double ellipse = new ...(x,y,width,height);
Answer: Ellipse2D.Double

43. Based on the following code, write four statements that draw a red square on a
yellow background.
public class RectangleComponent extends JComponent
{  public void paintComponent(Graphics g)
   {
     Graphics2D g2 = (Graphics2D) g;
     ...
   }
}
Answer:
g2.setBackground(Color.YELLOW);
Rectangle r = new Rectangle(0,0,10,10);
g2.setColor(Color.RED);
g2.draw(r);

44. The programmers who designed and implemented the library classes such as
PrintStream and Rectangle are called ...
Answer: A. System programmers

45. What is the missing code fragment in the following code?
public class CarComponent extends JComponent
{
   public void paintComponent(Graphics g)
   {
       Graphics2D g2 = (Graphics2D) g;
       Car car1 = new Car(0,0);
       int x = getWidth() - Car.WIDTH;
       int y = getHeight() - Car.HEIGHT;
       Car car2 = new Car(x,y);
       ...
   }
}
Answer: All Wrong
Explanation: Shouldn't the one that draws the component is the g2 variable
instead of the Car component?

46. It is a good idea to define ... for each complex shape that you want
to draw.
Answer: A separate class

47. Which of the following code fragments converts a floating-point number to the
nearest integer?
Answer:
B. double f = 4.65;
   int n = (int) Math.round(f);
explanation: You need a cast type to integer since Math.round(double) returns a
long.

48. The decimal equivalent of 110100 is ...
Answer: C. 52

49. The binary equivalent of 1000(decimal) is ...
Answer: A. 1111101000

50. Which of the following primitive types is a floating-point type with a size of
eight bytes?
Answer: B. double

51. Which of the following primitive types has a size of two bytes?
Answer: D. char

52. Which of the following code fragments will compile without error?
Answer:
B. int dollars = 100;
   double balance = dollars;
Explanation: Integer has less bytes than double. Therefore the system still works
to store a less bytes to a bigger bytes variable storage.

53. Consider the code fragment.
double balance = 13.75;
int dollars = balance;
Which of the following is true?
Answer: D. The code doesn't compile
Explanation: Double has bigger bytes than integer. Therefore the system can't store
a bigger bytes to a less bytes variable storage.

54. The binary equivalent of 200 is ...
Answer: D. 11001000

55. The decimal equivalent of 111010 is ...
Answer: A. 58

56. Which of the following correctly defines a constant in a method?
Answer: C. final double NICKEL_VALUE = 0.05;

57. Numerical ... are values that do not change and that have a special significance
for a computation.
Answer: constant 

58. Which of the following statements is equivalent to balance = balance + amount;?
Answer: A. balance += amount;

59. The value of x after the following sequence is ...
x--;x++;
Answer: The original value of x before the decrement or x+0

60. Consider this statement for computing the average of x,y, and z.
double average =  x + y + z / 3;
Which of the following statements is correct?
Answer: D. The code only gives the right answer when x = -y.
Explanation: To put it clear, the formula can be defined as x + y + (z /3).
Therefore, the computation computes the right average if the sum of x and y is 0.

61. A string is a sequence of ...
Answer: chars or characters

62. Convert the following string as price:
String input = "75.23";
Answer:
try {
  double price = Double.parseDouble(input);
}
catch(Exception e){} 

63. The ... method is used to extract a part of a string.
Answer: substring

64. The ... character is used as an escape character in Java.
Answer: \ or backslash

65. Java uses the ... encoding scheme to encode international characters.
Answer: Unicode




Counting Word Occurrence in a TextFile Using Efficient Storage For Faster Retrieval

27 08 2009

The previous day I applied for a position as a JAVA developer for Harita Mineral. I passed my second try in logic test after failing it in the first attempt. So, the next step was the technical test, where I was being judged on how I solve a problem by coding the real deal. The technical test for the company I applied was:

Goal of the Technical Test:
We are to see how you organize your thought, construct your code in accordance to good Object Oriented Programming’s Practice, and how you use data structure to store your data or search algorithm (if you use any) within the given problem.

Test:
You are to write a small Java Program to read and parse words from any given html file then store the words into the memory. User can search any words that he/she wishes to and the program will find the words from the memory and output the result of the search. Read the requirement below for more details.

Requirement:
1. User can enter file that they want the program to read. The file must be in the same directory as the class file.
2. User can enter word to be search as many times as they want
3. User can enter numerical number to give sign to program that they want to exit
4. Program will read and parse words in the given filename by user and store them in memory to search (output the measure time of reading and parsing words)
5. Program will output the number of occurrence of the word that users want to search if the word search exist in memory
6. Program will output the number of milliseconds needed to search the given word.
7. No database usage allowed.
8. Only 1 java file allowed
9. Only JDK Standard Edition (1.6) with standard API you can use to construct the program. (read as = no outside jars of standard issue JDK allowed)
10. Write the program within maximum 150 lines of code (don’t use any comment)

———
Example of Expected Output for the program:

C:>java RunTest
enter filename to read => overview-summary.html (user presses ENTER)
Total unique words = 1000 words – it takes 170 ms
enter word to search => java (user presses ENTER)
Found word java with total 20 occurrences in file overview-summary.html – it takes 90 ms
enter word to search => xml (user presses ENTER)
Found word xml with total 5 occurrences in file overview-summary.html – it takes 100 ms
enter word to search => harita (user presses ENTER)
Not found word harita in file overview-summary.html – it takes 200 ms
enter word to search => 1 (user presses ENTER)
Thank you for using RunTest
C:>

You have 3 days to submit your Java code starting from today.
You may ask questions to clarify any of the instructions written here.

So, to tackle this problem effectively we need to elaborate it into small pieces of tasks:

1. Deciding the correct library to use

We need a function to read input from keyboard as well as reading input from a file. Therefore, we need an input/ output library to handle this function which resides in the java.io. Next is to break the text we acquire from the defined file to only accept words. StreamTokenizer is a fast way to do this since you can define what characters to be a word, number, or symbol. StreamTokenizer also resides in java.io. Now, to store the words into a storage, we can use the library from java.util. The choices are many such as ArrayList, LinkedList, HashTable, HashMap, and so on. I personally choose HashMap since it can promote faster retrieval and element storing. I’ll be explaining more on this later.

So, in the first step, we got ourselves the code like this:

import java.io.*;
import java.util.*;

public class WordCount {
   public static void main (String[] args){

   }
}

2. Reading user input for what file to be read

Next, comes the problem to read user’s keyboard input. We need System.in to access the input from the command line and a converter called InputStreamReader to convert the input into readable format for JAVA and BufferedReader to convert it further to human readable format by calling the readline function in the BufferedReader class. Oh yeah, we need to catch an exception in accessing the readline function so you need a try method for that.

Anyway, here’s the code that you should have now:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

3. Reading the user-defined textFile

This is an easy one. You can use FileReader to access the specific file. However, you might want to also store it in the BufferedReader for the usage of StreamTokenizer class for defining delimiter to break down the sentence into words.

Therefore, the code now should be like this:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
         BufferedReader inputFile = new BufferedReader(new FileReader(inputText));
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

4. Breaking down the sentence into words

This is one of the core function that need’s to be sorted out, so read carefully. StreamTokenizer class provide a handy amount of features to store our input. The first you want to do is to put the file that has been read by the system in the BufferedReader to a newly invoked StreamTokenizer class. Next is to define what characters you want to consider as words and be stored in a public variable of StreamTokenizer called “sval”. To do this, reset all the characters by using resetSyntax function to put all the characters to ordinary characters. Then, use wordChars function to define which characters to be words. In this case, use wordChars(‘A’, ‘Z’) and wordChars(‘a’,'z’) to define all words to be alphabetic only. Now, to iterate all the words that has been stored, you can use nextToken function and check whether the token is a word by checking whether the value of token is StreamTokenizer.TT_WORD (constant type to indicate that the token is a word).

You now should have the code like this:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
         BufferedReader inputFile = new BufferedReader(new FileReader(inputText));
         StreamTokenizer st = new StreamTokenizer(inputFile);
         st.resetSyntax();
         st.wordChars('A','Z');
         st.wordChars('a','z');

         int found = StreamTokenizer.TT_WORD;
         String keyBuffer = "";
         while ((found != StreamTokenizer.TT_EOF))   {
            found = st.nextToken ();
            if(found == StreamTokenizer.TT_WORD) {
               String token = st.sval;
            }
         }
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

5. Storing the retrieved word into HashMap

We’re using HashMap because of the easiness and efficiency usage of this particular storage. HashMap introduce the concept of key and value, where to access a value that has been stored into the HashMap, you need a certain key value. Think of it as a door, where if you want to access to what inside the door, you’ll need a certain key to open the door. Therefore, we can use the word as the key and the number of occurence of that particular word as the value to the corresponding key.

Now, we need to always check whether the key (the word) has already stored in the HashMap. We can use the get function in the HashMap class to check whether key has already been registered to the HashMap. If the get function returned null, it means that it is a new word. Use the put function to store that word as the key and “1″ as the number of occurence of the value of the corresponding value.

On the other hand, if the get function do not return null, that means that the key has already been registered to the HashMap. Therefore we need to override the value of that particular key by using the put function. The brilliant thing about HashMap that it only allows unique keys to be registered. Any put function to an existing key will resulted in the value of the key to be overwrite.

Now, the code you have been doing so far, should be like this:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      HashMap<String,Integer> wordTank = new HashMap<String,Integer>();
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
         BufferedReader inputFile = new BufferedReader(new FileReader(inputText));
         StreamTokenizer st = new StreamTokenizer(inputFile);
         st.resetSyntax();
         st.wordChars('A','Z');
         st.wordChars('a','z');

         int found = StreamTokenizer.TT_WORD;
         String keyBuffer = "";
         while ((found != StreamTokenizer.TT_EOF))   {
            found = st.nextToken ();
            if(found == StreamTokenizer.TT_WORD) {
               String token = st.sval;
               if(wordTank.get(token) == null) {
                  wordTank.put(token,1);
               }
               else {
                  wordTank.put(token,wordTank.get(token)+1);
               }
            }
         }
         System.out.println("Total Unique words: " + wordTank.size());
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

6. Retrieving a word from user input

The next requirement is to provide a search feature to check whether a word that is typed by a user exists in the storage. If it exists, display the occurrence of that particular word. By now you should’ve guess that we need another readLine function to read user’s keyboard input. Since the search feature is repeated until the user types a numeric number to quit, put the next line code on an infinite loop and parse the user input into integer by using Integer.parseInt(string variable) function. If the input is a number, the system quits, while non-numeric will bring you to the retrievement of the word that is inputted by the user.

To retrieve the word in the storage, use the usual get function in the HashMap. If it returns null, that means the word that is being searched is not there and vice versa. So far, you should have this code now:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      HashMap<String,Integer> wordTank = new HashMap<String,Integer>();
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
         BufferedReader inputFile = new BufferedReader(new FileReader(inputText));
         StreamTokenizer st = new StreamTokenizer(inputFile);
         st.resetSyntax();
         st.wordChars('A','Z');
         st.wordChars('a','z');

         int found = StreamTokenizer.TT_WORD;
         String keyBuffer = "";
         while ((found != StreamTokenizer.TT_EOF))   {
            found = st.nextToken ();
            if(found == StreamTokenizer.TT_WORD) {
               String token = st.sval;
               if(wordTank.get(token) == null) {
                  wordTank.put(token,1);
               }
               else {
                  wordTank.put(token,wordTank.get(token)+1);
               }
            }
         }
         System.out.println("Total Unique words: " + wordTank.size());
         Integer occurrence;
         while(true) {
            System.out.print("Enter word to search => " );
            inputText = in.readLine();
            try {
               Integer.parseInt(inputText);
               System.out.println("Thanks for using WordCount");
               break;
            }
            catch(Exception e) {}
            occurrence = wordTank.get(inputText);
               if(occurrence != null) {
                  System.out.println("Found word " + inputText + " with total occurrences of " +
                     occurrence);
               }

               else{
                  System.out.println("Can't found word " + inputText + " in the file.");
               }
          }
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

7. Calculate your algorithm performance

Now, you need to test whether HashMap and StreamTokenizer can provide you faster storing and retrieving element in an array-like  structure. Use System.currentMillis() to get the current millisecond and put it between the start and the end of coding block that you want to analyze.

Now, the final code should be like this:

public class WordCount {
   public static void main (String[] args){
      String inputText = "";
      HashMap<String,Integer> wordTank = new HashMap<String,Integer>();
      System.out.print("Enter a filename to read: ");
      InputStreamReader converter = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(converter);
      try {
         inputText = in.readLine();
         long startTime = System.currentTimeMillis();
         long endTime;
         BufferedReader inputFile = new BufferedReader(new FileReader(inputText));
         StreamTokenizer st = new StreamTokenizer(inputFile);
         st.resetSyntax();
         st.wordChars('A','Z');
         st.wordChars('a','z');

         int found = StreamTokenizer.TT_WORD;
         String keyBuffer = "";
         while ((found != StreamTokenizer.TT_EOF))   {
            found = st.nextToken ();
            if(found == StreamTokenizer.TT_WORD) {
               String token = st.sval;
               if(wordTank.get(token) == null) {
                  wordTank.put(token,1);
               }
               else {
                  wordTank.put(token,wordTank.get(token)+1);
               }
            }
         }
         System.out.println("Total Unique words: " + wordTank.size() + " it takes " +
            (System.currentTimeMillis()-startTime) + " ms\n");
         Integer occurrence;
         while(true) {
            System.out.print("Enter word to search => " );
            inputText = in.readLine();
            try {
               Integer.parseInt(inputText);
               System.out.println("Thanks for using WordCount");
               break;
            }
            catch(Exception e) {}
            startTime = System.currentTimeMillis();
            occurrence = wordTank.get(inputText);
            endTime = System.currentTimeMillis();
               if(occurrence != null) {
                  System.out.println("Found word " + inputText + " with total occurrences of " +
                     occurrence + " in the file. It takes " + (endTime-startTime) + " ms.");
               }

               else{
                  System.out.println("Can't found word " + inputText + " in the file. It takes " +
                     (endTime-startTime) + " ms.");
               }
          }
      }

      catch(Exception e)  {
         System.out.println(""+e);
      }
   }
}

Test that with your desires text file. How fast did the algorithm perform in compare to using standard array and manual tokenizing?





JAVA Programming: Working With Swing Library

11 03 2009

Time for some JAVA action everyone. For today, let’s make an application interface that looks like this:

3-10-2009-2-54-56-pm

Step 1: Importing the library

To actually access the objects in the swing library, you have to import the swing library. So, start your JAVA file with:

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

Now, you have the access of swing objects and some additional object such as Listener object that will react on an event like mouse click or keyboard pressed.

Step 2: Constructing the class

Now, you have to choose the class name which will be the template of the application:

public class LibraryMDI implements ActionListener {

}

this class is named LibraryMDI and implements ActionListener. ActionListener is the event library that will provide you with the capability of listening to an event that user do in your application (in this case, we want the toolbar to react to a user’s mouse click). Now, you can save your work and name your class LibraryMDI.java.

Step 3: Constructing the frame

Just like any other application, the frame is a window to components in an application such as toolbar, menu, workspace, and any other else. To construct the frame, all you need to do is:

private JFrame frame;

public LibraryMDI() {
this.frame = new JFrame(“Library Information System”);

}

This will create a frame object that has a header title “Library Information System”.

Step 4: Arrange your frame for the components

Next, you will have to arrange your frame so that the components can be neatly placed in the frame. If you look at the picture, you will see that we need 4 space. The upper part where to put our toolbar icon, the middle part where the workspace will be placed, the right part where to put the logo image and memory monitor, and the bottom part to place the text “Library Information System — Created by Souza Nurafrianto IT5B”.

So, you have to define a panel and a layout for the panel to do this job. A panel is an invisible board which the components can be placed to it and layout is how the panel will arrange the components. So, define these components in your global variable:

private JPanel subMenu = new JPanel();
private BorderLayout subLayout = new BorderLayout();

We use BorderLayout as our layout because we only need to seperate four tiles in our panel (upper, middle, right, and bottom). BorderLayout does the job since it has up to 5 splitting tiles (north, west, center, east, and south). Consider the arrangement in the BorderLayout just like the compass: north for upper, west for right, etc. Now, you have to add four of the main components which will be placed in the subMenu panel (the toolbar, workspace, right panel, and bottom panel) as your global variable:

private JDesktopPane desktop = new JDesktopPane();

private JToolBar toolbar = new JToolBar(“Command Docker”, JToolBar.HORIZONTAL);

MessageBox box = new MessageBox(); // MessageBox class for right panel

private JPanel pMtitle = new JPanel();

Now, arrange these components into the your subMenu panel in your constructor class “public LibraryMDI()”:

subMenu.setLayout(subLayout);
subMenu.add(toolbar, BorderLayout.NORTH);
subMenu.add(this.desktop, BorderLayout.CENTER);
subMenu.add(box, BorderLayout.EAST);
subMenu.add(pMTitle, BorderLayout.SOUTH);

So, you have arranged these components into subMenu panel. Now, the subMenu panel has four components in it, toolbar which resides in the upper part, desktop which resides in the center (or right since WEST is not used), box which resides in the right, and pMTitle which resides in the bottom.

Step 5: Adding your toolbar some buttons

The toolbar that we just inserted in the subMenu panel still doesn’t have buttons, so let’s add a button. To define a button in swing you can use JButton:

private JButton btn1 = new JButton(new ImageIcon(getImage(“icon\\addItem.gif”)));

JButton can either receive ImageIcon or String. In this case, ImageIcon will put the button with a picture. You can also use a tool tip so that whenever you hover your mouse to the button, a text balloon will appear to describe what does the button do:

btn1.setToolTipText(“Order Resource”);

Next, put the button in the toolbar:

toolbar.add( btn1 );

Now, your toolbar has a button that can be pressed. However nothing will happen if you pressed it.

Step 6: Adding EventListener to the button

Now, you want the button to react if a user press on it, right? Remember that our LibraryMDI implements the ActionListener class? You can use the method to create a listener which will listen to any particular event done by the user. So, put the listener to the button:

btn1.addActionListener(this);
btn1.setActionCommand(“Order Resource”);

“this” in this context means that the button will go to the ActionListener of this particular class (the LibraryMDI class). Therefore, you have to define a method called “actionPerformed (ActionEvent e)” to catch any event that user’s made (if you don’t use “this”, the event that happened will not be catched by the actionPerformed of the LibraryMDI class). So, fill your method with this:

actionPerformed (ActionEvent e) {

String command = e.getActionCommand();

if (command.equals(“Order Resource”)) {
System.out.println(“Order Resource was pressed”);
}

}

Remember that we have defined if btn1 was pressed it will send a string “Order Resource” to the actionPerformed method (since you set the btn1.setActionCommand to be “Order Resource”). So, whenever ActionEvent contains “Order Resource” string, it knows that btn1 has been pressed by the user. Thus, the system will print “Order Resource was pressed” string in the command prompt.

Step 7: Inserting image to the workspace

Well, you want your workspace to have a background, right? Instead of plain white, you want to add logo and stuff to the workspace. To do this, just right this simple code:

Image a = Toolkit.getDefaultToolkit().getImage(System.getProperty(“user.dir”) + “\\image\\icon\\brokeBuckWall.jpg”);

this.desktop.setImage(a);

This will set the desktop with the image \image\icon\brockBuckWall.jpg.

Step 8: Putting it together to the frame

Now, your components are finished. Time to put it to the frame and show it to the world. Configure and place the subMenu panel to the frame:

this.frame.getContentPane().add(subMenu);
this.frame.setSize(1000,660);
this.frame.setResizable(false);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.show();

There you go your frame is done and ready for testing. Just do your usual “public void static main(String[] args)” and call on the object of LibraryMDI class.

Anyway, that was just a simple explanation how to do it. I’ll include the more sophisticated yet elegant way in the file that you can download below. Just execute the compile.bat to run the program.

File Name: Library Application (LISA)

File Size: 568 KB

Download: http://www.4shared.com/file/92343649/a1b6f2e5/LibraryApplication.html








Follow

Get every new post delivered to your Inbox.

Join 990 other followers