GlassFish Project - Java Persistence Example

by Son Rokhaniawan Perdata, S.T | 12:30 AM in | comments (0)

Overview

This is a very simple example that uses only 2 entities - a Customer and an Order, with OneToMany relationships between them. The Customer and the Order classes are Plain Old Java Classes (POJOs). These classes, as well as the code that manipulates POJO instances, can be used without any changes in Java SE or Java EE environment.

Accessing an EntityManagerFactory and an EntityManager depends on the environment and is described in more details below.

We will create a customer and two related orders, find the customer, and navigate from the customer to its orders, and then merge and remove all the objects. All these operation will be performed using Java Persistence API and require JDK 5.0.

Click here to get the ZIP file with the complete Java SE example as a netbeans project. This example works with Java DB or with Oracle.

Click here to get the ZIP file with the complete Java SE example. This example works with Oracle.

Click here to get the ZIP file with the complete Java EE example.

Refer to Java Persistence API document of JSR-220: Enterprise JavaBeansTM 3.0 Specification for further details on annotations and APIs.

Check example sources for the necessary import statements.



Mapping to Existing Tables

In the first example we will use only two tables:

CUSTOMER
ID
NAME


ORDER_TABLE
ORDER_ID
SHIPPING_ADDRESS
CUSTOMER_ID


CUSTOMER_ID column in the ORDER_TABLE is the Foreign Key (FK) to the ID column from the CUSTOMER table. The files sql/tables_oracle.sql and sql/tables_derby.sql in the example contains DDL to create both tables for Oracle and Apache Derby.

POJO Classes

Now let's look at the corresponding persistence classes. Both entities in this example use property based persistence. There is no access annotation element on the entity, so it defaults to access=PROPERTY. This is the reason why @Column annotation is specified for the get methods and not for the fields. The classes that are used as an argument or a return type between a remote client and a container must implement java.io.Serializable interface.
The POJO classes in the examples belong to an entity package.

Customer

The Customer entity is mapped to the CUSTOMER table, and looks like this:

@Entity
public class Customer {

private int id;
private String name;
private Collection
orders;

@Id
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public
String getName() {
return name;
}

public void setName(String
name) {
this.
name = name;
}


@OneToMany(cascade=ALL, mappedBy="customer")
public Collection getOrders() {
return orders;
}

public void setOrders(Collection newValue) {
this.orders = newValue;
}

}

Note that there are no @Table and @Column annotations. This is possible because the persistence provider will use the default rules to calculate those values for you. See chapter 9 of the Java Persistence API Specification for detailed rules of the mapping annotations.

Order

The Order entity is mapped to the ORDER_TABLE table. It requires both @Table and @Column mapping annotations because table and column names do not match class and properties names exactly. @Column annotations are specified for the corresponding get methods:

@Entity
@Table(name="ORDER_TABLE")

public class Order {

private int id;
private String address;
private Customer customer;

@Id
@Column(name="ORDER_ID")
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Column(name="SHIPPING_ADDRESS")
public String getAddress() {
return
address;
}

public void set
Address(String address) {
this.
address = address;
}


@ManyToOne()
@JoinColumn(name="CUSTOMER_ID")
public Customer getCustomer
() {
return
customer;
}

public void setCustomer
(Customer customer) {
this.
customer = customer;
}

}

Note that Customer and Order have bidirectional relationships between the entities.

Persisting POJO Entities

Now, let's create new instances, set up the relationships and persist all of them together using the CASCADE option that we set on the Customer entity. This code must be executed in a context of an active transaction.

// Create new customer
Customer customer0 = new Customer();
customer0.setId(1);
customer0.setName("Joe Smith");

// Persist the customer
em.persist(customer0);

// Create 2 orders
Order order1 = new Order();
order1.setId(100);
order1.setAddress("123 Main St. Anytown, USA");

Order order2 = new Order();
order2.setId(200);
order2.setAddress("567 1st St. Random City, USA");

// Associate orders with the customer.

Note that the association must be set on both sides of the relationship: on the customer side for the orders to be persisted when transaction commits, and on the order side because it is the owning side:

customer0.getOrders().add(order1);
order1.setCustomer(customer0);

customer0.getOrders().add(order2);
order2.setCustomer(customer0);

When this transaction commits, all three entities will be persisted in the database.

Query and Navigation

We'll use a new EntityManager to do the query, but will execute the query without an active transaction:

// Create new EntityManager
em = emf.createEntityManager();

Query q = em.createQuery("select c from Customer c where c.name = :name");
q.setParameter("name", "Joe Smith");

Our query is supposed to return a single customer, so we will use the Query method getSingleResult() to execute the query. This method would throw an exception if there is no or more than one matching customers.

Customer c = (Customer)q.getSingleResult();


Now let's verify that the orders were also created by navigating from the Customer.
You can print the orders, but we'll just check the size:

Collection orders = c.getOrders();
if (orders == null || orders.size() != 2) {
throw new RuntimeException("Unexpected number of orders: "
+ ((orders == null)? "null" : "" + orders.size()));
}

Merge and Removal of Persistent Instances

To remove an instance, it must be managed by this EntityManager. The code below uses a customer 'c' that had been detached from its persistence context. Removal of the Customer also removes related orders because of the CASCADE option set on the corresponding relationship. This code must be executed in a context of an active transaction.

// Merge the customer to the new persistence context
Customer c0 = em.merge(c);

Note that merge() is not a void operation. It returns back a managed copy of the argument (and its related objects). Only this copy can be used for EntityManager operations.

// Delete all records
em.remove(c0);

Putting It All Together

Using in Java SE

First, we need to create an EntityManagerFactory that we will use in the example. An EntityManagerFactory is created once for each PersistentUnit. Persistent unit in this example is called "pu1".

// Create EntityManagerFactory for persistent unit named "pu1"
// to be used in this test
emf = Persistence.createEntityManagerFactory("pu1");


For each business method in the example, a new EntityManager is created:

// Create new EntityManager
em = emf.createEntityManager();

If a transaction required, it is started:

// Begin transaction
em.getTransaction().begin();

And then the business logic is executed in a separate business method:

// Business logic
mybusinessmethod(...);

If transaction has been started it must be committed:

// Commit the transaction
em.getTransaction().commit();

And EntityManager should always be closed if it won't be used again:

// Close this EntityManager
em.close();

Java SE client code in this example is located in the class client.Client.

To run the test, you need to create META-INF/persistence.xml file in the classpath. Copy META-INF/persistence.xml.template file from the classes directory in the example to META-INF/persistence.xml and populate the values of the corresponding properties with the database settings that you are using. Note that persistence-unit name is set to "pu1" and all entity classes are explicitly listed.

Add your database driver and classes directory from the unzipped example to the classpath, load the tables into the database, then run:

java -javaagent:${glassfish.home}/lib/toplink-essentials-agent.jar client.Client

Using the Java SE Example in Netbeans

Configuring the JDBC driver

To configure the JDBC driver to be used when running the project, right-click on the project, select properties. Click on the libraries and then click on the 'Add JAR/Folder' button to add the jars for the JDBC driver being used. In the example below, the Java DB/Derby JDBC Client Driver is added.

Creating the tables

Scripts are provided to create the tables needed for the example for either Java DB/Derby or Oracle.

Note:If you are using Oracle, go to the runtime tab, click databases and then right click drivers to add the Oracle driver so that it can be used with the SQL Editor.

  • Create a connection to the database
    • expand the drivers folder and right click on the Oracle or Java DB/Derby driver and create a connection to the database. For Java DB/Derby you can enter: jdbc:derby://localhost:1527/testDB;create=true and enter APP for the username and password.
  • If you are using Java DB/Derby and the server is not started, Select Tools->Java DB Database ->Start Java DB server
  • Open the appropriate sql script by typing Ctrl-O or selecting 'Open File' from the file menu. The SQL scripts are in the sql directory of the project.
  • Select the connection to use (for Java DB/Derby you can use jdbc:derby://localhost:1527/testDB;create=true [APP on APP] .
  • Click the Run SQL icon on the right of the Connection drop-down box. This will open the Connect dialog. Enter the password for your connection. . Click OK to connect and run the SQL script.

Configuring the persistence unit

To configure the persistence unit for the sample, click on source packages and then click on META-INF. Double click on persistence.xml. Your configuration should look like the following if you are using Java DB/Derby:

Running the project:

To run the the sample application. Right click on the project and select 'Run Project'.

Using in Java EE

In a Java EE container, the client code will not create an EntityManagerFactory - it is done by the container.

There are several option to get a hold of an EntityManager:
  • An EntityManagerFactory or an EntityManager can be injected by the container or looked up in JNDI.
  • An EntityManager instance can be acquired from an EntityManagerFactory via the corresponding API call.
Transaction boundaries depend on the EntityManager type:
  • A JTA EntityManager participates in the current JTA transaction that is either controlled by the container or by a user via javax.transaction.UserTransaction API.
  • A resource-local EntityManager uses the same Java Persistence API as in Java SE environment to control its transactions.
In our example a JTA EntityManager is injected by the container into the Session Bean:

@PersistenceContext(unitName="pu1")
private EntityManager em;


Transaction boundaries set to container-managed defaults.

The client code from the Java SE example is now divided between a Stateless Session Bean ejb.TestBean (implements ejb.Test remote business interface), which contains the business logic (i.e. exactly the same business methods as the Java SE client), and an application client client.AppClient that calls the corresponding methods and prints the output:

// Persist all entities
System.out.println("Inserting Customer and Orders... " + sb.testInsert());

// Test query and navigation
System.out.println("Verifying that all are inserted... " + sb.verifyInsert());

// Get a detached instance
Customer c = sb.findCustomer("Joe Smith");

// Remove all entities
System.out.println("Removing all... " + sb.testDelete(c));

// Query the results
System.out.println("Verifying that all are removed... " + sb.verifyDelete());



In the Java EE environment META-INF/persistence.xml does not need to list persistence classes, or the (if you use the default persistence provider). It should specify , if it does not use the default DataSource provided by the container. The example specifies jdbc/__default, which is the default for the Derby database, so that it is easy to replace with another name. Java EE example uses automatic table generation feature in GlassFish by setting required properties in the META-INF/persistence.xml.

To test the example, unzip it and deploy ex1-ee.ear file:

${glassfish.home}/bin/asadmin deploy --retrieve . ex1-ee.ear

Then execute the appclient script:

${glassfish.home}/bin/appclient -client ./ex1-eeClient.jar -mainclass client.AppClient

The Result

This is the output (after several extra log messages) that will be printed:

Inserting Customer and Orders... OK
Verifying that all are inserted... OK
Removing all... OK
Verifying that all are removed... OK

[+/-] Read More...

Latest Jakarta News

by Son Rokhaniawan Perdata, S.T | 12:26 AM in | comments (0)

BluePrints Program

by Son Rokhaniawan Perdata, S.T | 12:29 AM in | comments (0)



Download Now Find a BluePrint
Discuss BluePrints About BluePrints

[+/-] Read More...

Mock exam 1

by Son Rokhaniawan Perdata, S.T | 3:53 PM in | comments (0)

The sample test is modeled on the Sun Certification for JavaTM 2 Programmer exam. The test has 59 questions and needs to be executed in 2 hours. The real exam may be a little tougher than this. You need to score 36 correct answers to clear the real exam. The first 50 questions of the mock exam are valid for both 1.2 and 1.4 versions of the exam. The remaining 9 questions are only useful if you are taking the SCJP 1.2 exam. Please let me know if you find any issues with the test. The site also offers another mock exam.


  1. Which declaration of the main method below would allow a class to be started as a standalone program. Select the one correct answer.


    1. public static int main(char args[])

    2. public static void main(String args[])

    3. public static void MAIN(String args[])

    4. public static void main(String args)

    5. public static void main(char args[])


  2. What all gets printed when the following code is compiled and run? Select the three correct answers.

  3.   public class xyz {    
    public static void main(String args[]) {
    for(int i = 0; i < 2; i++) {
    for(int j = 2; j>= 0; j--) {
    if(i == j) break;
    System.out.println("i=" + i + " j="+j);
    }
    }
    }
    }


    1. i=0 j=0

    2. i=0 j=1

    3. i=0 j=2

    4. i=1 j=0

    5. i=1 j=1

    6. i=1 j=2

    7. i=2 j=0

    8. i=2 j=1

    9. i=2 j=2


  4. What gets printed when the following code is compiled and run with the following command -

    java test 2

    Select the one correct answer.


  5.   public class test {    
    public static void main(String args[]) {
    Integer intObj=Integer.valueOf(args[args.length-1]);
    int i = intObj.intValue();
    if(args.length > 1)
    System.out.println(i);
    if(args.length > 0)
    System.out.println(i - 1);
    else
    System.out.println(i - 2);
    }
    }


    1. test

    2. test -1

    3. 0

    4. 1

    5. 2


  6. In Java technology what expression can be used to represent number of elements in an array named arr ?

  7. How would the number 5 be represented in hex using up-to four characters.


  8. Which of the following is a Java keyword. Select the four correct answers.


    1. extern

    2. synchronized

    3. volatile

    4. friend

    5. friendly

    6. transient

    7. this

    8. then


  9. Is the following statement true or false. The constructor of a class must not have a return type.


    1. true

    2. false


  10. What is the number of bytes used by Java primitive long. Select the one correct answer.


    1. The number of bytes is compiler dependent.

    2. 2

    3. 4

    4. 8

    5. 64


  11. What is returned when the method substring(2, 4) is invoked on the string "example"? Include the answer in quotes as the result is of type String.

  12. Which of the following is correct? Select the two correct answers.


    1. The native keyword indicates that the method is implemented in another language like C/C++.

    2. The only statements that can appear before an import statement in a Java file are comments.

    3. The method definitions inside interfaces are public and abstract. They cannot be private or protected.

    4. A class constructor may have public or protected keyword before them, nothing else.



  13. What is the result of evaluating the expression 14 ^ 23. Select the one correct answer.


    1. 25

    2. 37

    3. 6

    4. 31

    5. 17

    6. 9

    7. 24


  14. Which of the following are true. Select the one correct answers.


    1. && operator is used for short-circuited logical AND.

    2. ~ operator is the bit-wise XOR operator.

    3. | operator is used to perform bitwise OR and also short-circuited logical OR.

    4. The unsigned right shift operator in Java is >>.


  15. Name the access modifier which when used with a method, makes it available to all the classes in the same package and to all the subclasses of the class.

  16. Which of the following is true. Select the two correct answers.


    1. A class that is abstract may not be instantiated.

    2. The final keyword indicates that the body of a method is to be found elsewhere. The code is written in non-Java language, typically in C/C++.

    3. A static variable indicates there is only one copy of that variable.

    4. A method defined as private indicates that it is accessible to all other classes in the same package.


  17. What all gets printed when the following program is compiled and run. Select the two correct answers.



  18.   public class test {    
    public static void main(String args[]) {
    int i, j=1;
    i = (j>1)?2:1;

    switch(i) {
    case 0:
    System.out.println(0);
    break;
    case 1:
    System.out.println(1);
    case 2:
    System.out.println(2);
    break;
    case 3:
    System.out.println(3);
    break;
    }
    }
    }


    1. 0

    2. 1

    3. 2

    4. 3



  19. What all gets printed when the following program is compiled and run. Select the one correct answer.



  20.   public class test {    
    public static void main(String args[]) {
    int i=0, j=2;
    do
    {
    i=++i;
    j--;
    }
    while(j>0);
    System.out.println(i);
    }
    }


    1. 0

    2. 1

    3. 2

    4. The program does not compile because of statement "i=++i;"


  21. What all gets printed when the following gets compiled and run. Select the three correct answers.

      public class test {     
    public static void main(String args[]) {
    int i=1, j=1;
    try {
    i++;
    j--;
    if(i/j > 1)
    i++;
    }
    catch(ArithmeticException e) {
    System.out.println(0);
    }
    catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(1);
    }
    catch(Exception e) {
    System.out.println(2);
    }
    finally
    {
    System.out.println(3);
    }
    System.out.println(4);
    }
    }


    1. 0

    2. 1

    3. 2

    4. 3

    5. 4



  22. What all gets printed when the following gets compiled and run. Select the two correct answers.



  23.   public class test {     
    public static void main(String args[]) {
    int i=1, j=1;
    try {
    i++;
    j--;
    if(i == j)
    i++;
    }
    catch(ArithmeticException e) {
    System.out.println(0);
    }
    catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(1);
    }
    catch(Exception e) {
    System.out.println(2);
    }
    finally {
    System.out.println(3);
    }
    System.out.println(4);
    }
    }


    1. 0

    2. 1

    3. 2

    4. 3

    5. 4


  24. What all gets printed when the following gets compiled and run. Select the two correct answers.



  25.   public class test {     
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = "abc";
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    }
    }


    1. 1

    2. 2

    3. 3

    4. 4


  26. What all gets printed when the following gets compiled and run. Select the two correct answers.



  27.   public class test {     
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = new String("abc");
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    }
    }


    1. 1

    2. 2

    3. 3

    4. 4



  28. Which of the following are legal array declarations. Select the three correct answers.


    1. int i[5][];

    2. int i[][];

    3. int []i[];

    4. int i[5][5];

    5. int[][] a;


  29. What is the range of values that can be specified for an int. Select the one correct answer.


    1. The range of values is compiler dependent.

    2. -231 to 231 - 1

    3. -231-1 to 231

    4. -215 to 215 - 1

    5. -215-1 to 215


  30. How can you ensure that the memory allocated by an object is freed. Select the one correct answer.


    1. By invoking the free method on the object.

    2. By calling system.gc() method.

    3. By setting all references to the object to new values (say null).

    4. Garbage collection cannot be forced. The programmer cannot force the JVM to free the memory used by an object.



  31. What gets printed when the following code is compiled and run. Select the one correct answer.



  32.   public class test {     
    public static void main(String args[]) {
    int i = 1;
    do {
    i--;
    }
    while (i > 2);
    System.out.println(i);
    }
    }


    1. 0

    2. 1

    3. 2

    4. -1


  33. Which of these is a legal definition of a method named m assuming it throws IOException, and returns void. Also assume that the method does not take any arguments. Select the one correct answer.


    1. void m() throws IOException{}

    2. void m() throw IOException{}

    3. void m(void) throws IOException{}

    4. m() throws IOException{}

    5. void m() {} throws IOException


  34. Which of the following are legal identifier names in Java. Select the two correct answers.


    1. %abcd

    2. $abcd

    3. 1abcd

    4. package

    5. _a_long_name


  35. At what stage in the following method does the object initially referenced by s becomes available for garbage collection. Select the one correct answer.



  36.   void method X()  {      
    String r = new String("abc");
    String s = new String("abc");
    r = r+1; //1
    r = null; //2
    s = s + r; //3
    } //4


    1. Before statement labeled 1

    2. Before statement labeled 2

    3. Before statement labeled 3

    4. Before statement labeled 4

    5. Never.


  37. String s = new String("xyz");

    Assuming the above declaration, which of the following statements would compile. Select the one correct answer.


    1. s = 2 * s;

    2. int i = s[0];

    3. s = s + s;

    4. s = s >> 2;

    5. None of the above.



  38. Which of the following statements related to Garbage Collection are correct. Select the two correct answers.


    1. It is possible for a program to free memory at a given time.

    2. Garbage Collection feature of Java ensures that the program never runs out of memory.

    3. It is possible for a program to make an object available for Garbage Collection.

    4. The finalize method of an object is invoked before garbage collection is performed on the object.


  39. If a base class has a method defined as

    void method() { }

    Which of the following are legal prototypes in a derived class of this class. Select the two correct answers.


    1. void method() { }

    2. int method() { return 0;}

    3. void method(int i) { }

    4. private void method() { }


  40. In which all cases does an exception gets generated. Select the two correct answers.



  41. int i = 0, j = 1;


    1. if((i == 0) || (j/i == 1))

    2. if((i == 0) | (j/i == 1))

    3. if((i != 0) && (j/i == 1))

    4. if((i != 0) & (j/i == 1))



  42. Which of the following statements are true. Select the two correct answers.


    1. The wait method defined in the Thread class, can be used to convert a thread from Running state to Waiting state.

    2. The wait(), notify(), and notifyAll() methods must be executed in synchronized code.

    3. The notify() and notifyAll() methods can be used to signal and move waiting threads to ready-to-run state.

    4. The Thread class is an abstract class.


  43. Which keyword when applied on a method indicates that only one thread should execute the method at a time. Select the one correct answer.


    1. transient

    2. volatile

    3. synchronized

    4. native

    5. static

    6. final


  44. What is the name of the Collection interface used to represent elements in a sequence (in a particular order). Select the one correct answer.


    1. Collection

    2. Set

    3. List

    4. Map



  45. Which of these classes implement the Collection interface SortedMap. Select the one correct answers.


    1. HashMap

    2. Hashtable

    3. TreeMap

    4. HashSet

    5. TreeSet

    6. Vector


  46. Which of the following are true about interfaces. Select the two correct answers.


    1. Methods declared in interfaces are implicitly private.

    2. Variables declared in interfaces are implicitly public, static, and final.

    3. An interface can extend any number of interfaces.

    4. The keyword implements indicate that an interface inherits from another.


  47. Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer.


    1. test();

    2. super.test();

    3. super.super.test();

    4. ::test();

    5. C.test();

    6. It is not possible to invoke test() method defined in C from a method in A.


  48. What is the return type of method round(double d) defined in Math class.


  49. What gets written on the screen when the following program is compiled and run. Select the one right answer.

  50.   public class test {    
    public static void main(String args[]) {
    int i;
    float f = 2.3f;
    double d = 2.7;
    i = ((int)Math.ceil(f)) * ((int)Math.round(d));
    System.out.println(i);
    }
    }


    1. 4

    2. 5

    3. 6

    4. 6.1

    5. 9


  51. Is the following statement true or false. As the toString method is defined in the Object class, System.out.println can be used to print any object.


    1. true

    2. false


  52. Which of these classes defined in java.io and used for file-handling are abstract. Select the two correct answers.


    1. InputStream

    2. PrintStream

    3. Reader

    4. FileInputStream

    5. FileWriter


  53. Name the collection interface used to represent collections that maintain unique elements.


  54. What is the result of compiling and running the following program.

  55.   public class test {    
    public static void main(String args[]) {
    String str1="abc";
    String str2="def";
    String str3=str1.concat(str2);
    str1.concat(str2);
    System.out.println(str1);
    }
    }


    1. abc

    2. def

    3. abcabc

    4. abcdef

    5. defabc

    6. abcdefdef


  56. Select the one correct answer. The number of characters in an object of a class String is given by


    1. The member variable called size

    2. The member variable called length

    3. The method size() returns the number of characters.

    4. The method length() returns the number of characters.


  57. Select the one correct answer. Which method defined in Integer class can be used to convert an Integer object to primitive int type.


    1. valueOf

    2. intValue

    3. getInt

    4. getInteger


  58. Name the return type of method hashCode() defined in Object class, which is used to get the unique hash value of an Object.

  59. Which of the following are correct. Select the one correct answer.


    1. An import statement, if defined, must always be the first non-comment statement of the file.

    2. private members are accessible to all classes in the same package.

    3. An abstract class can be declared as final.

    4. Local variables cannot be declared as static.



  60. Name the keyword that makes a variable belong to a class, rather than being defined for each instance of the class. Select the one correct answer.


    1. static

    2. final

    3. abstract

    4. native

    5. volatile

    6. transient


  61. Which of these are core interfaces in the collection framework. Select the one correct answer.


    1. Tree

    2. Stack

    3. Queue

    4. Array

    5. LinkedList

    6. Map



  62. Which of these statements are true. Select the two correct answers.


    1. For each try block there must be at least one catch block defined.

    2. A try block may be followed by any number of finally blocks.

    3. A try block must be followed by at least one finally or catch block.

    4. If both catch and finally blocks are defined, catch block must precede the finally block.


    The remaining questions are related to AWT, event classes, and layout managers. These topics are not included in 1.4 version of the exam.



  63. The default layout manager for a Frame is ...


    1. FlowLayout

    2. BorderLayout

    3. GridLayout

    4. GridBagLayout

    5. CardLayout


  64. Which of the following are valid adapter classes in Java. Select the two correct answers.


    1. ComponentAdapter

    2. ActionAdapter

    3. AdjustmentAdapter

    4. ItemAdapter

    5. FocusAdapter


  65. Which method defined in the EventObject class returns the Object that generated an event. The method should be given in the format - return_type method_name();

  66. Which of the following object receives ActionEvent. Select the four correct answers.


    1. List

    2. Button

    3. Choice

    4. CheckBox

    5. TextField

    6. MenuItem


  67. Name the class that may be used to create submenus in pull-down menus.

  68. In which class is the wait() method defined. Select the one correct answer.


    1. Applet

    2. Runnable

    3. Thread

    4. Object


  69. Which is the only layout manager that always honors the size of a component. Select the one correct answer.


    1. FlowLayout

    2. GridLayout

    3. BorderLayout

    4. CardLayout

    5. GridBagLayout


  70. Which of these are valid Event Listener interfaces. Select the two correct answers.


    1. MouseMotionListener

    2. WindowListener

    3. DialogListener

    4. PaintListener


  71. Which abstract class is the super class of all menu-related classes.




Answers to Sample Test 1



  1. b

  2. b, c, f

  3. d. Note that the program gets one command line argument - 2. args.length will get set to 1. So the condition if(args.length > 1) will fail, and the second check if(args.length > 0) will return true.

  4. arr.length

  5. Any of these is correct - 0x5, 0x05, 0X05, 0X5


  6. b, c, f, g

  7. a

  8. d

  9. "am"

  10. a, c. Please note that b is not correct. A package statement may appear before an import statement. A class constructor may be declared private also. Hence d is incorrect.


  11. a

  12. a

  13. protected

  14. a, c

  15. b, c


  16. c

  17. a, d, e

  18. d, e

  19. a, c

  20. b, c


  21. b, c, e

  22. b

  23. d


  24. a

  25. a

  26. b, e . The option c is incorrect because a Java identifier name cannot begin with a digit.

  27. d

  28. c


  29. c, d

  30. a, c

  31. b, d


  32. b, c

  33. c

  34. c


  35. c

  36. b, c

  37. f

  38. long


  39. e

  40. a

  41. a, c

  42. Set


  43. a

  44. d

  45. b

  46. int

  47. d


  48. a

  49. f

  50. c, d

  51. b

  52. a, e

  53. Object getSource();

  54. a, b, e, f

  55. Menu

  56. d

  57. a

  58. a, b

  59. MenuComponent


[+/-] Read More...

Making Http Simple Server With Java

by Son Rokhaniawan Perdata, S.T | 12:16 AM in , | comments (2)

Praktikum's task Network and Apparatus Mathematics moves secondly be make one http simple server at localhost. With utilize SocketServer's function, therefore gets to be made one server which will wait â€Å“panggilan” on port 80 (HTTP). And will send html's code while called.

SocketServer works in one looping that perpetual to wait marks sense connection to go to port 80 on localhost. There is 4 constructor on SocketServer for example:

  1. public ServerSocket(int port) throws BindException, IOException
  2. public ServerSocket(int port, int queueLength) throws BindException, IOException
  3. public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException
  4. public ServerSocket( ) throws IOException // Java 1.4

n Java, to make one server gets to be done by trick as follows:

  1. One serverSocket a new one is made deep one given port (in this case port 80) utilizing constructor of one SocketServer.
  2. Then serverSocket waits until mark sense coming connection through port has already is determined previous utilize accept's function().
  3. Then depends from server type, well utilize getInputStream's function(), getOutputStream's function(), or both of ala function goes together to get input and output stream in order to gets communication with client.
  4. Server and client gets communication / get interaction until its time hang up connection.
  5. Server, Client or both hangs up connection
  6. Server returns to to step 2 and waiting until marks sense succeeding connections.

And attachment source's following code that I takes from praktikum's module meagrely modifies to be able to qualify as one http server.

Serverku.java

[+/-] Read More...

Perusal and File Writing with Java

by Son Rokhaniawan Perdata, S.T | 12:03 AM in , | comments (0)

A few days ago, my friend asks for to help her works PR its Programming. PR's problem terminologicals i am goodly difficult also, since I newbie in programming. Programming languages who may be utilized is C,C++, Java. And since i am java person, therefore I choose to utilize Java.hehe.. Since I really be intend to study Java language.

Problem PR is we make program who will read one input file “indata.txt”, one that meaty word which will at test do correspond to order, if accords therefore that diwrite will into one file “legalwords.txt”, conversely if incorrectly will at write into file “badwords.txt”. Among word one by another word in file “indata.txt” came to pieces by one tabulator, on my program, I utilize tabulator tab(\t). Order that is utilized for mengetest to say is

a. first syllable may not as numeral as.
b. say has less than 8 characters.
c. say just may lap over of letter (a..z, A..Z), number (0..9), atau simbol underscore(’_').

Since I newbie in Java,and was wonted utilizes it, requiring time rather long time to think up syntax syntax that is used. On progam I, its program path is as follows:

a. Make one BufferedReader for FileReader(”indata.txt”). Make PrintWritter for FileWriter legalwords.txt and badwords.txt.
b. Then by use of StringTokenizer to account word amount in file indata.txt.
c. After knows total token / says, therefore then with looping to check about word / token, what appropriate ruling or not.
d. Then afters is sorted, therefore word suitably at write goes to legalwords.txt, and unsuitably diwrite goes to badwords.txt

And this is result running programs my version:
1. Input File

Input File

2. Legal Words

Input File

3. Bad Words

Input File

On Compile NetBeans

Input File

And this following is source code programs what do I make. Its correction appeal if available fault.

DOWNLOAD


[+/-] Read More...

Tips Java : Getting Address's IP and Host Name

by Son Rokhaniawan Perdata, S.T | 11:35 PM in , | comments (0)

Java provides InetAddress's function to get host's internet protocol address and also name a computer. host's internet protocol address and also name that is gotten don't cling to host's internet protocol address and name local computer only, but can also be utilized for mengecek host's internet protocol address and name at Internet, obviously by condition of computer we most link with Internet. This logistic purpose also relates hand in glove with setting DNS on computer that we utilizes.

Following is sample program that points out fungsionalitas that:
  1. Make one project is Netbeans new

  2. Add one JFrame Form

  3. Provede with 2 tags, 2 numbers TextField (txtIPAddress dan txtNamaHost) and 3 Button (btnCheckIPAddress, btnCheckHostName dan btnCheckLokal). See example on pictured following:

  4. Following code cannikin type on btnCheckHostName, event actionPerformed

    1. private void btnCheckHostNameActionPerformed(java.awt.event.ActionEvent evt) {

    2. try {

    3. String strHostName = InetAddress.getByName(txtIPAddress.getText()).getHostName();

    4. JOptionPane.showMessageDialog(null, "Host name dari IP Address '" + txtIPAddress.getText() +"' =
      "+ strHostName);

    5. } catch (UnknownHostException ex) {

    6. JOptionPane.showMessageDialog(null, ex);

    7. Logger.getLogger(frmIpAddress.class.getName()).log(Level.SEVERE, null, ex);


    8. }


    9. }


  5. Do import library that needful (import java.net.InetAddress; import javax.swing.JOptionPane;)

  6. Following code cannikin type on btnCheckIPAddress, event actionPerformed


    1. private void btnCheckIPAddressActionPerformed(java.awt.event.ActionEvent evt) {


    2. try {

    3. String strIPAddress = InetAddress.getByName(txtHostName.getText()).getHostAddress() ;

    4. JOptionPane.showMessageDialog(null, "Alamat IP dari '"+txtHostName.getText() +"' ="+ strIPAddress);

    5. } catch (UnknownHostException ex) {

    6. JOptionPane.showMessageDialog(null, ex);

    7. Logger.getLogger(frmIpAddress.class.getName()).log(Level.SEVERE, null, ex);


    8. }

    9. }


  7. Following code cannikin type on btnCheckLokal event actionPerformed

    1. private void btnCheckLocalActionPerformed(java.awt.event.ActionEvent evt) {

    2. try {

    3. InetAddress AlamatInternet = InetAddress.getLocalHost();

    4. JOptionPane.showMessageDialog(null, "Host name lokal : " +AlamatInternet.getHostName());

    5. JOptionPane.showMessageDialog(null, "IP Address lokal : " +AlamatInternet.getHostAddress() );

    6. } catch (UnknownHostException ex) {

    7. JOptionPane.showMessageDialog(null, ex);

    8. Logger.getLogger(frmIpAddress.class.getName()).log(Level.SEVERE, null, ex);


    9. }

    10. }


  8. Save and runs application (SHIFT + F6). Insert IP Address and click on “Check Host Name” or insert host name and click “Check IP Address”. Check IP and Host Local don't need entry. Following is umpteen screenshot message one that performs:



    This program not smart's ala detect entry what that internet protocol address or host name. To easy, I utilize 2 numbers TextField for example. On terapan's application, input IP Address or Host Name can thru get variable.

[+/-] Read More...

Creating an AJAX-Enabled Calendar Control

by Son Rokhaniawan Perdata, S.T | 12:08 AM in | comments (0)


Introduction
Go to any travel or event booking website and you'll find the same user interface for collecting date information: the Calendar. Providing such an interface in an ASP.NET application is a breeze, thanks to the built-in Calendar Web control. There are two downsides to ASP.NET's Calendar control: first, it is not very useful when selecting dates far into the future or past, as you can only navigate to the next or previous month; and, second, the Calendar does not use AJAX techniques, so each click, be it selecting a date or moving to the next or previous month, requires a full postback.

Mehmet Genc addressed this first shortcoming in Extending the Calendar Control's Date Navigation by showing how to add month and year drop-down lists. But Mehmet's article was written in 2004 and since then AJAX-enabled websites have become all the rage. I decided it was high time to update Mehmet's custom Calendar control to support AJAX. Specifically, I implemented the AJAX-enabled Calendar control as a User Control. The User Control renders a TextBox control that, when clicked, displays a Calendar control from which the user can select the date. Like with Mehmet's Calendar, users can quickly jump to a particular month or year by using two drop-down lists. And best of all, the user experience is very responsive.

First Things First: Ensuring Your Environment Supports ASP.NET AJAX
To use this AJAX-enabled Calendar control, make sure your development environment supports the ASP.NET AJAX framework. If you are using Visual Studio 2008, then this framework is already present. If, however, you are using Visual Studio 2005, then you need to download and install the ASP.NET AJAX framework from Microsoft's site, http://www.asp.net/ajax/. For more information on this process, refer to Scott Mitchell's article, AJAX Basics and Getting Started with Microsoft's ASP.NET AJAX Framework.

My AJAX-enabled Calendar control uses the UpdatePanel and PopupControlExtender controls. While the UpdatePanel is part of the framework's "Essential Components," the PopupControlExtender is part of the ASP.NET AJAX Control Toolkit, which is a separate download (even for Visual Studio 2008). If you check out the Control Toolkit samples you'll notice that there's an AJAX Calendar control in the Toolkit. I built my own AJAX-enabled Calendar control instead of using the one in the Control Toolkit because I wanted to add the month/year drop-down lists. Also, there have been a variety of display bugs with the Calendar control (see the AJAX Control Toolkit work item list). I invite you to try out mine and the AJAX Control Toolkit's Calendar and use the one that's best suited for your needs.

Getting Started with My AJAX-Enabled Calendar Control
The complete code for this User Control, along with a sample web page, is available at the end of this article. You should be able to open the folder as a website in either Visual Studio 2005 or Visual Studio 2008.

The Calendar is implemented in the CoolCalendar.ascx file as a User Control. Take a moment to examine the markup in this page. You'll find the following key controls:

1. The DateTextFrom TextBox
2. A RequiredFieldValidator named DateTextFromRequired
3. A Panel control
4. An UpdatePanel control
5. The month and year DropDownList controls
6. The Calendar control
7. An AJAX PopupControlExtender control

There are a few of these controls that warrant further discussion. Take note of the markup for the DateTextFrom TextBox control (item 1):


Note the onfocus="javascript:this.blur();".

This bit of client-side script ensures that whenever the user clicks on the DateTextFrom TextBox, focus is immediately taken away from the control. The idea here - as we'll see shortly - is that whenever the user focuses on the TextBox it is immediately taken away and the Calendar control is displayed. This forces the user to select a date from the calendar. If you remove the onfocus script, the user could enter the date into the TextBox via the keyboard. I find this option undesirable due to the possibility of user entry errors.

The RequiredFieldValidator (item 2) is used to optionally ensure that a date value has been supplied. The User Control contains a Boolean public property named DateTextRequired. Setting this value to True enables the RequiredFieldValidator; setting it to False disables it. By default, the RequiredFieldValidator is enabled.

The AJAX PopupControlExtender control pops up a particular Panel on the page in response to a certain client-side action. The Panel control (item 3) defines the region that is popped up, and includes the UpdatePanel (item 4), the month/year DropDownLists (item 5), and the Calendar control (item 6).

The final piece in the markup page is the PopupControlExtender control (item 7) and is configured to display the Panel (item 3) whenever the DateTextFrom TextBox receives focus. This behavior is dictated entirely through the PopupControlExtender control's properties, there's no need to write any JavaScript or code!


For more information on the PopupControlExtender see the PopupControlExtender Demonstration. Also check out Brian Smith's article

, Displaying Extended Details in a GridView Using an Ajax Pop-Up.

Examining the AJAX-Enabled Calendar Control's Code
The User Control's code-behind class defines a couple of properties and includes the code to populate the month/year DropDownLists and the user's interactions with the Calendar. The most important property is the DateTextFromValue, which sets or gets the selected date. This property simply reads and writes its value to the DateTextFrom TextBox.

public string DateTextFromValue
{
get { return DateTextFrom.Text; }
set { DateTextFrom.Text = value; }
}

Note: The code available for download at the end of this article includes a VB and C# version of the User Control...

Two additional properties are defined for specifying whether the RequiredFieldValidator should be enabled (DateTextRequired) and the error message to display if the required date value is not supplied (DateTextRequiredText).

The month and year DropDownLists are populated by the Populate_MonthList and Populate_YearList methods, which are called on the first page visit. These methods were taken directly from Mehmet's article. Populate_MonthList returns a list of month names (January, February, ...) while Populate_YearList populates the DropDownList with years from 20 years ago to one year in the future.

When the month or year DropDownList is changed, a partial page postback occurs and the Set_Calendar method is executed. The Set_Calendar method sets the Calendar control's TodaysDate property to the first of the selected month/year.

public void Set_Calendar(object Sender, EventArgs E)
{
string theDate = drpCalMonth.SelectedItem.Value + " 1, " + drpCalYear.SelectedItem.Value;

DateTime dtFoo;
dtFoo = System.Convert.ToDateTime(theDate);

Calendar1.TodaysDate = dtFoo;
}

Whenever the user selects a date within the Calendar, a partial page postback transpires and the Calendar's SelectionChanged event is fired. The Calendar1_SelectionChanged event handler calls the PopupControlExtender control's Commit method, passing in the Calendar's SelectedDate property. The net effect is that the Calendar popup disappears and the selected date is display in the TextBox.

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
PopupControlExtender1.Commit(Calendar1.SelectedDate.ToShortDateString());
}

My AJAX-Enabled Calendar Web Control In Action
The download at the end of this article includes a simple demo page, TestCoolCalendar.aspx. The demo illustrates how to use the User Control's DateTextRequired and DateTextRequiredText properties to require a date and show a custom error message. In addition to the User Control, the TestCoolCalendar.aspx includes a Save button that, when clicked, displays the value selected from the Calendar control. This value is retrieved via the User Control's DateTextFromValue property.

Conclusion
In this article we saw how to use the ASP.NET AJAX framework's UpdatePanel and the AJAX Control Toolkit's PopupControlExtender to turn the built-in Calendar control into a richer, AJAX-enabled version. This control is implemented as a User Control, making it a cinch to add to your projects. Thanks again to Mehmet Genc for the initial inspiration and to Scott Mitchell for publishing this article.

Happy Programming!

[+/-] Read More...

Calculator modestly with Swing

by Son Rokhaniawan Perdata, S.T | 2:00 PM in | comments (0)



Swing is one of technology in Java to make one application desktop. This following I load one simple example with swing. One calculator plain. I utilize two numbers class. Class first is that of penampil frame and class second is program from that calculator is alone.

Its example following:

package testing;

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

/**
*
* @author bagus
*/
public class SwingCalculator {
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Then remakes one class at same package

package testing;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* @author bagus
*/
class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();

public Calculator() {
textfield = new JTextField("0", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST );
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("0");
equalOp = "=";
op.setTotal("0");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (number) {
action();
textfield.setText("0");
} else {
number = true;
String displayText = textfield.getText();
if (equalOp.equals("=")) {
op.setTotal(displayText);
} else if (equalOp.equals("+")) {
op.add(displayText);
} else if (equalOp.equals("-")) {
op.subtract(displayText);
} else if (equalOp.equals("*")) {
op.multiply(displayText);
} else if (equalOp.equals("/")) {
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp {

private int total;
public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}
public void divide(String n) {
total /= convertToNumber(n);
}
private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}
}


Its output result is as follows:


[+/-] Read More...

Create Database with Netbeans Program and Ms.Access

by Son Rokhaniawan Perdata, S.T | 11:32 PM in , | comments (0)

Hi all readers, this project we will create a database program using Netbeans IDE 6.5 Database and Ms.Access. Software may Netbeans is new for us. Yes the actual program Netbeans is a software used to create a program based on JAVA. We still use the first appearance of white Notepad to create JAVA applications. Akan NotePad but parallel development is replaced by slow start because TEXTPAD facilities provided by this TEXTPAD seems more complete and informative than the notepad. But when we look kebelakang shortages have appeared TEXTPAD again, that is we still have to type the script to make the program components. And that lack is covered by the Netbeans this. Namely to provide component parts without having to type the script to make the withdrawal other GUI Programming Languages. You can create our new project, we:

Here the view that the program will be created:


The Steps:

***> Create database tables and cooperation with the Member as follows:

==================================================================

Noang - Text - 5

Nama - Text - 25

Alamat - Text - 30

Jkel - Yes/no

Agama - Text - 1

NoKTP - Text - 15

NoTelp - Text - 12

Simpanan - Number - LongInt

============================================================

1. Create a design form as shown in the picture. In the form there is a component JTextField, JComboBox, JRadioButton, JPanel, JButton.
2. Change the name of the components that we have entered, especially for components JTextField, JComboBox, JButton, JRadioButton engan way and conditions as follows:

[+/-] Read More...

NetBeans IDE Java Quick Start Tutorial (Hello Word)

by Son Rokhaniawan Perdata, S.T | 11:10 AM in , , | comments (0)

Welcome to NetBeans IDE!

This tutorial provides a very simple and quick introduction to the NetBeans IDE workflow by walking you through the creation of a simple "Hello World" Java console application. Once you are done with this tutorial, you will have a general knowledge of how to create and run applications in the IDE.

This tutorial takes less than 10 minutes to complete.

After you finish this tutorial, you can move on to the learning trails, which are linked from the Documentation, Training & Support page. The learning trails provide comprehensive tutorials that highlight a wider range of IDE features and programming techniques for a variety of application types. If you do not want to do a "Hello World" application, you can skip this tutorial and jump straight to the learning trails.

To complete this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE version 6.5
Java Development Kit (JDK) version 6 or
version 5

Setting Up the Project

To create an IDE project:

  1. Start NetBeans IDE.
  2. In the IDE, choose File > New Project (Ctrl-Shift-N), as shown in the figure below.

    New Project menu item selected." class="margin-around" height="85" width="199">

  3. In the New Project wizard, expand the Java category and select Java Application as shown in the figure below. Then click Next. NetBeans IDE, New Project wizard, Choose Project page.
  4. In the Name and Location page of the wizard, do the following (as shown in the figure below):
    • In the Project Name field, type HelloWorldApp.
    • Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
    • In the Create Main Class field, type helloworldapp.HelloWorldApp.
    • Leave the Set as Main Project checkbox selected.

    NetBeans IDE, New Project wizard, Name and Location page.

  5. Click Finish.

The project is created and opened in the IDE. You should see the following components:

  • The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
  • The Source Editor window with a file called HelloWorldApp open.
  • The Navigator window, which you can use to quickly navigate between elements within the selected class.
  • The Tasks window, which lists compilation errors as well other tasks that are marked with keywords such as XXX and TODO.

NetBeans IDE with the HelloWorldApp project open.

Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:

            // TODO code application logic here
with the line:
            System.out.println("Hello World!");

Save the change by choosing File > Save.

The file should look something like the following code sample.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloworldapp;

/**
*
* @author Patrick Keegan
*/
public class HelloWorldApp {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}

}

Compiling and Running the Program

Because of the IDE's Compile on Save feature, you do not have to manually compile your project in order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.

To run the program:

  • Choose Run > Run Main Project (F6).

The next figure shows what you should now see.

The program prints Hello World! to the Output window (along with other output from the build script).

Congratulations! Your program works!

If there are compilation errors, they are marked with red glyphs in the left and right margins of the Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs in the right margin show all of the areas of the file that have errors, including errors in lines that are not visible. You can mouse over an error mark to get a description of the error. You can click a glyph in the right margin to jump to the line with the error.

Building and Deploying the Application

Once you have written and test run your application, you can use the Clean and Build command to build your application for deployment. When you use the Clean and Build command, the IDE runs a build script that performs the following tasks:

  • Deletes any previously compiled files and other build outputs.
  • Recompiles the application and builds a JAR file containing the compiled files.

To build your application:

  • Choose Run > Clean and Build Main Project (Shift-F11).

You can view the build outputs by opening the Files window and expanding the HelloWorldApp node. The compiled bytecode file HelloWorldApp.class is within the build/classes/helloworldapp subnode. A deployable JAR file that contains the HelloWorldApp.class is within the dist node.

Image showing the Files window with the nodes for the HelloWorldApp          expanded to show the contents of the build and dist subnodes.

[+/-] Read More...

About Me

My photo
I am its person simple. Bad blood platitude. Directly az goes to aim target

Shoutbox