Showing posts with label net beans ide. Show all posts
Showing posts with label net beans ide. Show all posts

Saturday, 24 December 2011

Running the SavingsAccountEJB Example

Setting Up the Database

The instructions that follow explain how to use the SavingsAccountEJB example with a Cloudscape database. The Cloudscape software is included with the J2EE SDK download bundle.
  1. From the command-line prompt, run the Cloudscape database server by typing cloudscape -start. (When you are ready to shut down the server, type cloudscape -stop.)
  2. Create the savingsaccount database table.
    1. Go to the j2eetutorial/examples directory
    2. Type ant create-savingsaccount-table.
You may also run this example with databases other than Cloudscape. (See the Release Notes of the J2EE SDK for a list of supported databases.) If you are using one of these other databases, you may run the j2eetutorial/examples/sql/savingsaccount.sql script to create the savingsaccount table.

Deploying the Application

  1. In deploytool, open the j2eetutorial/examples/ears/SavingsAccountApp.ear file (FileOpen).
  2. Deploy the SavingsAccountApp application (ToolsDeploy). In the Introduction dialog box, make sure that you select the Return Client JAR checkbox.

Running the Client

  1. In a terminal window, go to the j2eetutorial/examples/ears directory.
  2. Set the APPCPATH environment variable to SavingsAccountAppClient.jar.
  3. Type the following command on a single line:
    runclient -client SavingsAccountApp.ear -name
          SavingsAccountClient -textauth
     
    
  4. At the login prompts, enter guest for the user name and guest123 for the password.
  5. The client should display the following lines:
    balance = 68.25
       balance = 32.55
       456: 44.77
       730: 19.54
       268: 100.07
       836: 32.55
       456: 44.77
       4.00
       7.00

Remote Interface

The remote interface extends javax.ejb.EJBObject and defines the business methods that a remote client may invoke. Here is the SavingsAccount remote interface:
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import java.math.BigDecimal;

public interface SavingsAccount extends EJBObject {
    
    public void debit(BigDecimal amount)
        throws InsufficientBalanceException, RemoteException;

    public void credit(BigDecimal amount)
        throws RemoteException;
 
    public String getFirstName()
        throws RemoteException;

    public String getLastName()
        throws RemoteException;
   
    public BigDecimal getBalance()
        throws RemoteException;
}
 
The requirements for the method definitions in a remote interface are the same for both session and entity beans:
  • Each method in the remote interface must match a method in the enterprise bean class.
  • The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class.
  • The arguments and return values must be valid RMI types.
  • The throws clause must include java.rmi.RemoteException.
A local interface has the same requirements, with the following exceptions:
  • The arguments and return values are not required to be valid RMI types.
  • The throws clause does not include java.rmi.RemoteException.

Database Calls

Table 5-1 summarizes the database access calls in the SavingsAccountBean class. The business methods of the SavingsAccountBean class are absent from the preceding table because they do not access the database. Instead, these business methods update the instance variables, which are written to the database when the EJB container calls ejbStore. Another developer might have chosen to access the database in the business methods of the SavingsAccountBean class. This choice is one of those design decisions that depend on the specific needs of your application.
Before accessing a database, you must connect to it.
Table 5-1 SQL Statements in SavingsAccountBean 
MethodSQL Statement
ejbCreateINSERT
ejbFindByPrimaryKeySELECT
ejbFindByLastNameSELECT
ejbFindInRangeSELECT
ejbLoadSELECT
ejbRemoveDELETE
ejbStoreUPDATE

Home Methods

A home method contains the business logic that applies to all entity beans of a particular class. In contrast, the logic in a business method applies to a single entity bean, an instance with a unique identity. During a home method invocation, the instance has neither a unique identity nor a state that represents a business object. Consequently, a home method must not access the bean's persistence state (instance variables). (For container-managed persistence, a home method also must not access relationships.)
Typically, a home method locates a collection of bean instances and invokes business methods as it iterates through the collection. This approach is taken by theejbHomeChargeForLowBalance method of the SavingsAccountBean class. The ejbHomeChargeForLowBalance method applies a service charge to all savings accounts with balances less than a specified amount. The method locates these accounts by invoking the findInRange method. As it iterates through the collection of SavingsAccount instances, theejbHomeChargeForLowBalance method checks the balance and invokes the debit business method. Here is the source code of the ejbHomeChargeForLowBalance method:
public void ejbHomeChargeForLowBalance(
    BigDecimal minimumBalance, BigDecimal charge) 
    throws InsufficientBalanceException {

   try {
       SavingsAccountHome home =
       (SavingsAccountHome)context.getEJBHome();
       Collection c = home.findInRange(new BigDecimal("0.00"),
           minimumBalance.subtract(new BigDecimal("0.01")));

       Iterator i = c.iterator();

       while (i.hasNext()) {
          SavingsAccount account = (SavingsAccount)i.next();
          if (account.getBalance().compareTo(charge) == 1) {
             account.debit(charge);
          }
       }

   } catch (Exception ex) {
       throw new EJBException("ejbHomeChargeForLowBalance: " 
           + ex.getMessage());
   } 
} 
 
The home interface defines a corresponding method named chargeForLowBalance. Since the interface provides the client view, the SavingsAccountClientprogram invokes the home method as follows:
SavingsAccountHome home;
...
home.chargeForLowBalance(new BigDecimal("10.00"), 
   new BigDecimal("1.00"));
 
In the entity bean class, the implementation of a home method must adhere to these rules:
  • A home method name must start with the prefix ejbHome.
  • The access control modifier must be public.
  • The method modifier cannot be static.
The throws clause may include exceptions that are specific to your application; it must not throw the java.rmi.RemoteException.

ejbLoad and ejbStore Methods

If the EJB container needs to synchronize the instance variables of an entity bean with the corresponding values stored in a database, it invokes the ejbLoad and ejbStore methods. TheejbLoad method refreshes the instance variables from the database, and the ejbStore method writes the variables to the database. The client may not call ejbLoad and ejbStore.
If a business method is associated with a transaction, the container invokes ejbLoad before the business method executes. Immediately after the business method executes, the container callsejbStore. Because the container invokes ejbLoad and ejbStore, you do not have to refresh and store the instance variables in your business methods. The SavingsAccountBean class relies on the container to synchronize the instance variables with the database. Therefore, the business methods of SavingsAccountBean should be associated with transactions.
If the ejbLoad and ejbStore methods cannot locate an entity in the underlying database, they should throw the javax.ejb.NoSuchEntityException. This exception is a subclass ofEJBException. Because EJBException is a subclass of RuntimeException, you do not have to include it in the throws clause. When NoSuchEntityException is thrown, the EJB container wraps it in a RemoteException before returning it to the client.
In the SavingsAccountBean class, ejbLoad invokes the loadRow method, which issues a SQL SELECT statement and assigns the retrieved data to the instance variables. The ejbStoremethod calls the storeRow method, which stores the instance variables in the database with a SQL UPDATE statement. Here is the code for the ejbLoad and ejbStore methods:
public void ejbLoad() {

   try {
      loadRow();
   } catch (Exception ex) {
      throw new EJBException("ejbLoad: " + 
         ex.getMessage());
   }
}

public void ejbStore() {

   try {
      storeRow();
   } catch (Exception ex) {
      throw new EJBException("ejbStore: " + 
         ex.getMessage());
   }
}

ejbRemove Method

A client deletes an entity bean by invoking the remove method. This invocation causes the EJB container to call the ejbRemove method, which deletes the entity state from the database. In theSavingsAccountBean class, the ejbRemove method invokes a private method named deleteRow, which issues a SQL DELETE statement. The ejbRemove method is short:
public void ejbRemove() {
    try {
        deleteRow(id);
    catch (Exception ex) {
        throw new EJBException("ejbRemove: " +
        ex.getMessage());
    }
}
 
If the ejbRemove method encounters a system problem, it should throw the javax.ejb.EJBException. If it encounters an application error, it should throw a javax.ejb.RemoveException. 
An entity bean may also be removed directly by a database deletion. For example, if a SQL script deletes a row that contains an entity bean state, then that entity bean is removed.

ejbPostCreate Method

For each ejbCreate method, you must write an ejbPostCreate method in the entity bean class. The EJB container invokes ejbPostCreate immediately after it calls ejbCreate. Unlike theejbCreate method, the ejbPostCreate method can invoke the getPrimaryKey and getEJBObject methods of the EntityContext interface. For more information on the getEJBObjectmethod. Often, your ejbPostCreate methods will be empty.
The signature of an ejbPostCreate method must meet the following requirements:
  • The number and types of arguments must match a corresponding ejbCreate method.
  • The access control modifier must be public.
  • The method modifier cannot be final or static.
  • The return type must be void.
The throws clause may include the javax.ejb.CreateException and exceptions that are specific to your application.

Friday, 23 December 2011

What Is RPC?

 RPC is remote procedure calls. Where RMI lets you interoperate directly with a Java object, RPC is built in more of a dispatch fashion. Instead of dealing with objects, RPC lets you use standalone methods across a network. Although this limits interactivity, it does make for a slightly simpler interface to the client. You can think of RPC as a way to use "services" on remote machines, while RMI allows you to use "servers" on remote machines. The subtle difference is that RMI typically is driven entirely by the client, with events occurring when methods are invoked remotely. RPC is often built more as a class or set of classes that works to perform tasks with or without client intervention; however, at times these classes service requests from clients, and execute "mini" tasks for the clients. I will show you some examples shortly to clarify these definitions.
RPC, while not as interactive an environment as RMI, does offer some significant advantages. RPC allows disparate systems to work together. While RMI allows the use of IIOP for connecting Java to CORBA servers and clients, RPC allows literally any type of application intercommunication, because the transport protocol can be HTTP. Since virtually every language in use today has some means of communicating via HTTP, RPC is very attractive for programs that must connect to legacy systems. RPC is also typically more lightweight than RMI (particularly when using XML as the encoding, which I'll cover next); while RMI often has to load entire Java classes over the network (such as code for applets and custom helper classes for EJB), RPC only has to pass across the request parameters and the resulting response, generally encoded as textual data. RPC also fits very nicely into the API model, allowing systems that are not part of your specific application to still access information from your application. This means that changes to your server do not have to result in changes to other clients' application code; with pure textual data transfer and requests, additional methods can be added without client recompilation, and minor changes are sufficient to use these new methods.
The problem with RPC has traditionally been the encoding of data in transfer; imagine trying to represent a Java Hashtable or Vector in a very lightweight way through textual formats. When you consider that these structures can, in turn, hold other Java object types, the data representation quickly becomes tricky to write; it also has to remain a format that is usable by all the disparate programming languages, or the advantages of RPC are lessened. Until recently, an inverse relationship had been developing between the quality and usability of the encoding and its simplicity; in other words, the easier it became to represent complex objects, the more difficult it became to use the encoding in multiple programming languages without proprietary extensions and code. Elaborate textual representations of data were not standardized and required completely new implementations in every language to be usable. You can see where this discussion is leading.
See XML-RPC
Learn about What is RMI?

Thursday, 15 December 2011

Install JDK on the Client


The client system is defined as the system where you execute the JServer tools, such as loadjava, deployejb. You can use the same system for both your client and server.
The client system requires JDK 1.1.6 or later. Solaris 2.6 bundles JDK 1.1.3, which does not work with our samples. Verify that your PATH includes JDK 1.1.6 or later and does not include JDK 1.1.3. To confirm what version of the JDK you are using, perform the following:
$ which java
/usr/local/packages/jdk1.1.6/bin/java 
$ which javac 
/usr/local/packages/jdk1.1.6/bin/javac 
$ java -version
java version "1.1.6"
If JDK 1.1.6 does not appear within these commands, either put your JDK 1.1.6 installation at the start of PATH or remove the 1.1.3 installation. In addition, check your CLASSPATH for references to the incorrect JDK version.


Note:
All Oracle8i Java-based client tools work in the Java 2 environment.  


Tuesday, 6 December 2011

Link to Install Netbeans


Required Downloads

Warning: This section is probably outdated and applies only to version 6.5 and needs update.
NetBeans requires quite a lot Java programs. As such, there are some programs from Sun which require an agreement check box to be ticked before download, ergo there are files that must be downloaded manually. The links to those files are provided here for your convenience:

x86 Architecture

These downloads are only needed if you do not have java5 flag enabled either globally or for dev-java/tomcat-servlet-api, dev-java/aspectwerkz and dev-java/jdbc-postgresql packages.
  • Download j2sdk-1_4_2_18-linux-i586.bin from:
  • Download jce_policy-1_4_2.zip from:

All Architectures

  • Download sjp-1_0-fr-ri.zip from:
http://jcp.org/aboutJava/communityprocess/final/jsr223/index.html (Click on Download button under the Reference Implementation and Technology Compatibility Kit heading.)

Once the downloads have completed, the only thing you need to do is move them to /usr/portage/distfiles/.

Portage

If you are on stable arch (so not using ~arch packages) and NetBeans is still in ~arch, you need to put dev-util/netbeans and other needed ~arch packages into/etc/portage/package.keywords. See
man 5 portage
for details. Simply said, you need to put every package that is needed for emerge of NetBeans but masked with ~arch into your /etc/portage/package.keywords.

Selecting USE Flags


If you do not need JavaDoc API documentation for NetBeans sources, make sure to disable -doc USE flag. Building documentation for NetBeans sources can take a lot of time.
Since netbeans-6.9-r3, you can turn on support for keychain by enabling keychain. If you enable this, you will be able to benefit from keychain in NetBeans when connecting to ssh protected remote repositories. When you start NetBeans (from menu, from run window or from terminal, does not really matter), keychain will be run and keys that you can optionally specify will be added to ssh-agent and you will be prompted for key passwords if the keys are not managed yet. This is the first and last time NetBeans will ask you for key passwords. To specify keys that you want to add to ssh-agent on NetBeans startup, create file keychain-keys.txt in your userdir (by default ~/.netbeans/6.9/) and put on each line single key that you want to load.
File: ~/.netbeans/6.9/keychain-keys.txt
id_dsa
id_dsa_gentoo


Netbeans


NetBeans is popular open-source and free IDE that runs on Windows, Linux, Mac OS X and Solaris and includes support for several programming and scripting languages. You can find more info about NetBeans at http://netbeans.org. At this moment, the latest version of NetBeans that we have on Gentoo is 6.9. Latest stable version is 6.8. This guide generally applies to Netbeans since version 6.5 and does not describe installation of older versions of NetBeans. Also please note that NetBeans 6.9 is currently masked by ~arch so it is not by default available for those on stable archs. (If you want to install latest NetBeans on stable arch, you can find info in this article too, just read on.)
In Gentoo, NetBeans is currently available for amd64 and x86 systems. If you want NetBeans also for other archs, file a bug at http://bugs.gentoo.org/

Monday, 5 December 2011

Java VM


Monitoring and Management of the Java Virtual Machine
The JMX technology can also be used to monitor and manage the Java virtual machine (Java VM).
The Java VM has built-in instrumentation that enables you to monitor and manage it by using the JMX technology. These built-in management utilities are often referred to as out-of-the-box management tools for the Java VM. To monitor and manage different aspects of the Java VM, the Java VM includes a platform MBean server and special MXBeans for use by management applications that conform to the JMX specification.

Platform MXBeans and the Platform MBean Server

The platform MXBeans are a set of MXBeans that is provided with the Java SE platform for monitoring and managing the Java VM and other components of the Java Runtime Environment (JRE). Each platform MXBean encapsulates a part of Java VM functionality, such as the class-loading system, just-in-time (JIT) compilation system, garbage collector, and so on. These MXBeans can be displayed and interacted with by using a monitoring and management tool that complies with the JMX specification, to enable you to monitor and manage these different VM functionalities. One such monitoring and management tool is the Java SE platform's JConsole graphical user interface (GUI).
The Java SE platform provides a standard platform MBean server in which these platform MXBeans are registered. The platform MBean server can also register any other MBeans you wish to create.

JConsole

The Java SE platform includes the JConsole monitoring and management tool, which complies with the JMX specification. JConsole uses the extensive instrumentation of the Java VM (the platform MXBeans) to provide information about the performance and resource consumption of applications that are running on the Java platform.

Out-of-the-Box Management in Action

Because standard monitoring and management utilities that implement the JMX technology are built into the Java SE platform, you can see the out-of-the-box JMX technology in action without having to write a single line of JMX API code. You can do so by launching a Java application and then monitoring it by using JConsole.

Monitoring an Application by Using JConsole

This procedure shows how to monitor the Notepad Java application. This procedure assumes that you are running the Java SE 6 platform.
  1. Start the Notepad Java application, by using the following command in a terminal window:
    java -jar jdk_home/demo/jfc/Notepad/Notepad.jar
    Where jdk_home is the directory in which the Java Development Kit (JDK) is installed.
  2. Once Notepad has opened, in a different terminal window, start JConsole by using the following command:
    jconsole
    A New Connection dialog box is displayed.
  3. In the New Connection dialog box, select Notepad.jar from the Local Process list, and click the Connect button.JConsole opens and connects itself to the Notepad.jar process. When JConsole opens, you are presented with an overview of monitoring and management information related to Notepad. For example, you can view the amount of heap memory the application is consuming, the number of threads the application is currently running, and how much central procesing unit (CPU) capacity the application is consuming.
  4. Click the different JConsole tabs.Each tab presents more detailed information about the different areas of functionality of the Java VM in which Notepad is running. All the information presented is obtained from the various JMX technology MXBeans mentioned in this trail. All the platform MXBeans can be displayed in the MBeans tab. The MBeans tab is examined in the next section of this trail.
  5. To close JConsole, select Connection -> Exit.

Saturday, 19 November 2011

MySQL WorkBench

You need MySQL workbench to register on netbeans. As netbeans will by default not have Register MySQL db enabled for you. Configuring that would require the GUI tool for MySQL

Visit MySQL GUI Tools Downloads to download

Thursday, 10 November 2011

Automatic window lifecycle management


A further major advantage of the NetBeans Window System is that it provides a WindowManager that controls the lifecycle of all the windows defined in the application. The WindowManager notifies allTopComponents about state changes using callback methods, listed as follows:

componentOpened()It is called after the TopComponent has been opened. If multiple TopComponents are opened into the same position (called mode), the NetBeans Window System uses a tabbed container, with one TopComponent per tab. Of all available TopComponents found within a shared tabbed container, only the content of the selected TopComponent is visible.
componentShowing()It notifies the component that its content is now visible. This TopComponent is now either selected or is the only component in a separate container.
componentActivated()It is called after the TopComponent has gained the input focus or has become the selected component.
componentDeactivated()It is called after the TopComponent has lost the input focus.
componentHidden()It notifies the TopComponent that its content is no longer visible.
componentClosed()It is called after the TopComponent has been closed.
Let's illustrate this lifecycle via an example that logs all the callback methods to the output window of NetBeans IDE, which is your development environment on top of the NetBeans Platform.
  1. Create a new NetBeans Platform application and name it WindowSystemExamples.
  2. Add a new module named LifeCycle, with Code Name Base com.netbeansrcp.lifecycle.
  3. Add a TopComponent, with Class Name Prefix prefix LifeCycleDemo, making sure to indicate that it should be automatically opened in the editor area at application startup.
  4. Override the lifecycle methods as follows:
    public void componentOpened() { super.componentOpened(); System.out.println("componentOpened()"); } protected void componentShowing() { super.componentShowing(); System.out.println("componentShowing()"); } protected void componentActivated() { super.componentActivated(); System.out.println("componentActivated()"); } @Override protected void componentDeactivated() { super.componentDeactivated(); System.out.println("componentDeactivated()"); } @Override protected void componentHidden() { super.componentHidden(); System.out.println("componentHidden()"); } @Override public void componentClosed() { super.componentClosed(); System.out.println("componentClosed()"); }
Start the new application. The TopComponent LifeCyleDemoTopComponent is automatically opened at startup. Select the TopComponent and inspect the output in the NetBeans IDE Output Window. You should see the following:
componentOpened() componentShowing() componentActivated()
The TopComponent has passed the first half of its lifecycle and is now activated.
Close the LifeCyleDemoTopComponent and inspect the output again, to understand the second half of the TopComponent lifecycle. You should see the following output:
componentHidden() componentDeactivated() componentClosed()
You have learned that the TopComponent's lifecycle is automatically controlled by the NetBeans Platform. Between the start and the end of the TopComponent's lifecycle are six different states, all managed by the NetBeans Platform, and with notifications sent via callbacks.

Programmatically managing the Window lifecycle

You can manage the lifecycle of a TopComponent programmatically. For this purpose, theTopComponent provides the following methods:
  • open(): Opens the TopComponent
  • requestVisible(): Requests to select to TopComponent
  • requestActive(): Requests to transfer the input focus to the TopComponent
Let's now modify the LifeCycleDemoTopComponent for demonstration purposes.
  1. Add a JButton to the TopComponent, as follows:
  2. Implement an ActionEventListener as follows:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { this.close(); RequestProcessor.getDefault().post(new java.lang.Runnable() { public void run() { java.awt.EventQueue.invokeLater(new java.lang.Runnable() { public void run() { com.netbeansrcp.lifecycle.LifeCycleDemoTopComponent.this.open(); } }); } }, 3000); RequestProcessor.getDefault().post(new java.lang.Runnable() { public void run() { java.awt.EventQueue.invokeLater(new java.lang.Runnable() { public void run() { com.netbeansrcp.lifecycle. LifeCycleDemoTopComponent.this.requestActive(); } }); } }, 6000); }
  3. Restart the application. When you click the button, the LifecycleDemoTopComponent is closed via the close() method, called above in the first line of the code you entered.
The RequestProcessor provides a thread pool. The default instance of this pool lets you execute aRunnable after a short delay, thanks to the post() method. As the TopComponent's lifecycle method should be called from the AWT event thread, you do not call them directly in the run() method, but by posting a new Runnable to the EventQueue, which in the end calls the Window System API methods.
The argument 3000 ensures that the execution of the Runnable is delayed for 3000 ms so that theTopComponent is opened again after 3 s.
After six seconds the second Runnable posted to the EventQueue is executed and requestActive() is called for your LifecycleDemoTopComponent. Your TopComponent is now shown in the foreground, if it had been behind other windows previously.
You have learned how to manage the lifecycle of a TopComponent. Via the example you have seen how to open a TopComponent and make it focusable.

Positioning of windows

The NetBeans Window System divides the available space in the main window into areas that are called "modes". Each mode represents a specific area of the main window, providing a container for windows in a predefined position in the frame. You can add windows, that is, TopComponents, to a mode, either declaratively or programmatically.
A standard layout is provided by the NetBeans Window System, corresponding to the layout of NetBeans IDE. For example, the predefined modes correspond to the names used in the corresponding positions in NetBeans IDE, such as "editor" and "explorer". If needed, you can define your own modes, too. No wizard is provided for this purpose in NetBeans IDE, so you need to create the mode definition files yourself manually.
In the previous section you learned about the layer.xml file. To create a default layout for an application, each TopComponent needs to be declaratively registered within the Windows2 | Modes folder, within a subfolder named after the mode in which the TopComponent should be docked.
To demonstrate declarative registration of TopComponents, edit the layer.xml in the LifeCycle module, changing the folder name Windows2 | Modes | editor to Windows | Modes | rightSlidingSide, as shown in the following code snippet:
layer.xml // <folder name="Windows2"> <folder name="Components"> <file name="LifecycleDemoTopComponent.settings" url="LifecycleDemoTopComponentSettings.xml"/> </folder> <folder name="Modes"> <folder name="rightSlidingSide"> <file name="LifecycleDemoTopComponent.wstcref" url="LifecycleDemoTopComponentWstcref.xml"/> </folder> </folder> </folder> //
Select Clean and Build on the application node in the Projects window, to remove the build folder containing the last used window layout, and start the application again. When the application starts up, notice that the LifecycleDemoTopComponent is not opened in the editor mode. Instead, it is represented by a button on the right sidebar of the application (as shown in the screenshot below). That is therightSlidingSide mode, providing a container for minimized windows.
As you have seen, providing a default layout via declarative registrations of TopComponents is rather easy. You only need to create an entry in the layer.xml for the TopComponent, in a folder with the name of the desired mode, within the Windows2 | Modes folder.
Sometimes declarative registration alone is too static for your business needs. Fortunately, positioning ofTopComponents can also be done programmatically. In the next example, you create a TopComponentthat moves to new modes via a click of a button.
  1. Add to the WindowSystemExamples application a new module named Modes, with the Code Name Base com.netbeansrcp.modes.
  2. Within the module, create a TopComponent called ModesDemo, which is opened when the application starts into the "editor" mode.
Add two JButtons to the TopComponent with the texts Back and Forward, as well as a JLabel with an empty initial text. The TopComponent should look as shown in the following screenshot:
In the Source view, add the following code:
private static final String[] MODES = new String[] { "properties", "commonpalette", "rightSlidingSide", "bottomSlidingSide", "output", "debugger", "navigator", "explorer", "leftSlidingSide", "editor" }; private void changeMode(boolean next) { Mode currentMode = WindowManager.getDefault().findMode(this); String currentModeName = currentMode.getName(); String nextModeName = "editor"; for (int i = 0; i < MODES.length; i++) { String modeName = MODES[i]; if (modeName.equals(currentModeName)) { if (next) { nextModeName = (i + 1 < MODES.length) ? MODES[i + 1] : MODES[0]; } else { nextModeName = (i - 1 >= 0) ? MODES[i - 1] : MODES[MODES.length - 1]; } break; } } Mode nextMode = WindowManager.getDefault().findMode(nextModeName); if (nextMode != null) { this.jLabel1.setText(nextModeName); nextMode.dockInto(this); this.open(); this.requestActive(); } } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { this.changeMode(true); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { this.changeMode(false); }
The static string array contains the names of the most important modes. These modes can also be identified dynamically, by calling WindowManager.getDefault().getModes().
The ActionListener delegates the call to the method changeMode() and gives the desired back/forward direction. This method determines via WindowManager.getDefault ().findMode (this) the mode in which theTopComponent is displayed, as well as the name of the current mode.
The string array is then searched and dockInto(this) is called to dock the TopComponent into a different mode.
How to revert to the default layout?
As the layout of the NetBeans Platform is persisted when the application shuts down, first perform a Clean and Build on the application project. With the removal of the build folder, the layout settings are also deleted, so that the default layout is used when the application starts again.
Using the two buttons, you can let the TopComponent be docked in some of the most commonly used modes (as shown in the screenshot below).
You have programmatically docked a TopComponent into various places within the available modes in the application. In the process, you have learned how TopComponents can be docked dynamically, that is, at runtime, into desired positions. Both the declarative and the programmatic approaches to docking should now be familiar to you.