Practical eclipse system class that provides shortcuts for RCP

Source: Internet
Author: User

Introduction:Eclipse provides the RCP Application Development kernel, which already provides many useful classes. You can familiarize yourself with and use these classes to reduceCodeYou can also improve the robustness of your code. Since RCP runs on the eclipse kernel, try to use as many built-in classes as possible. For example, saferunner provides the log exception function, and busyindicator can block mouse events so that the currentProgramFocus on one thing, instead of making the program die, and the mouse turns into a funnel. This article will introduce these classes as much as possible, and use the sample code to demonstrate their usage. I believe that you can master their usage skills in this article.

 

Introduction

RCP (rich client platform) is a powerful open development platform provided by eclipse to developers. It allows eclipse-based applications to be developed in the same style as Eclipse. Because it is based on Eclipse, many useful System Classes in eclipse can be used in the developer's own RCP application, which not only reduces the development volume, but also greatly improves the system stability. This article introduces some eclipse System Classes used by the author in actual development. A detailed understanding of these classes can provide shortcuts for your RCP development.

Back to Top

Introduction to category

This article will introduce several Category classes one by one, in the following order.

    • Saferunner usage
    • Busyindicator usage
    • Preferencesutil usage
    • Idialogsettings usage
    • Filelocator usage
    • Workbenchhelp usage
    • Messagedialogwithtoggle usage
    • Imemento in viewpart
    • Re-recognize the display class

Each part of the List describes the specific usage of a category class,ArticleThe attachment contains the sample code used by these classes. The sample code for each category class is named "Class Name" + usecase. java. To make it easier for you to view the effect, the sample code of each class in the Attachment Program has a corresponding button. You can click the corresponding button to view the effect, as shown in interface 1 of the Attachment Program. You can import the attachment to the eclipse workspace to run it.


Figure 1. Sample program interface

Back to Top

Saferunner usage

In Java Development, statements written in many cases may throw an exception, which requires programmers to write a try... A catch statement that contains exception statements and processes exceptions in the catch statement block. Exceptions thrown during RCP applications must be recorded in the log file for future query, perform other operations as needed. The traditional method is used to handle exceptions in RCP, not just try... Catch statements, you also need to write the code that records eclipse logs. If there are more exception statements, the code will become bloated and hard to understand.

Eclipse provides a class named saferunner, which allows developers to put Exception Code into the run method of saferunner for execution. By default, saferunner adds try... Catch statement to capture exceptions and record exceptions. At the same time, saferunner allows developers to perform other operations on exceptions. Shows how to use saferunner.

Listing 1. Use of saferunner

System. out. println ("Statement 1"); saferunner. run (New isaferunnable () {@ override public void run () throws exception {// execution location of the exception code system. out. println ("Statement 2 (exceptions may be thrown)"); throw new runtimeexception ("exception in statement 2") ;}@ override public void handleexception (throwable exception) {// other Exception Handling Methods. printstacktrace () ;}}); system. out. println ("Statement 3 ");

 

In the handleexception method, you can perform other operations on exceptions, such as printing exception information and recording it to the database.

When the code in Listing 1 is executed in the RCP application, its log file records the thrown exceptions, as shown in effect 2.

Figure 2. log files using the saferunner

Saferunner is used to normalize RCP Exception Handling, reduce the amount of code, and make it easier to maintain. You do not need to write your own log record code.

Back to Top

Busyindicator usage

When you try to execute a thread task and the main thread stops waiting until the task execution is completed, developers generally want to use the display Sync method to put the task into the main thread for execution, the disadvantage of such execution is that the main thread stops responding when the task is executed, giving people the feeling that the program is dead. Therefore, to solve this problem, you can use busyindicator to execute the task. This allows the mouse to display a funnel chart during task execution, marking that the main thread is busy and the actual task is executed in another thread. Click the "busyindicator" button in the attachment program to display the use effect of busyindicator. The executed code is shown in listing 3.

Listing 2. Sample Code of busyindicator

Public static void handleclick (Button button) {button. settext ("running... "); busyindicator. showwhile (button. getdisplay (), new sleepthread (5000); button. settext ("busyindicator");} static class sleepthread extends thread {private long MS; Public sleepthread (long MS) {This. ms = MS;} public void run () {try {sleep (MS);} catch (interruptedexception e ){}}}

 

Click the "busyindicator" button to change the label of the "busyindicator" button to running... In sleepthread, use the sleep method of the thread to simulate the task execution for 5 seconds. During task execution, although the main program does not respond, there is no sense that the program is dead, and the Mouse shows a funnel. After the task is executed, the button label is restored to "busyindicator", and the mouse arrow is also restored to normal.

Back to Top

Preferencesutil usage

Eclipse provides a preference extension point that allows developers to define their own preferences and integrate them into eclipse (for details about how to extend the preferences, see the official eclipse development documentation). Normally, you can use the window-> preferences menu of eclipse to open all the preferences, and then find the custom preferences page. However, if the developer wants to open the custom preferencesutil page in other ways, the preferencesutil must be used. This class provides the function to open the specified preferences page, the attachment defines a preference, ID: testpreferencesutilpage, name: Test preferencesutil page, and Listing 4 is the method code to use preferencesutil to open the preferred page with ID: testpreferencesutilpage.

Listing 3. Sample Code of preferencesutil

Preferencedialog createpreferencedialogon = preferencesutil. createpreferencedialogon (null, "testpreferencesutilpage", null, null); createpreferencedialogon. open ();

 

You can click "preferencesutil" in the attachment program to view the effect, as shown in figure 3.

Figure 3. preferencesutil example

Back to Top

Idialogsettings usage

Idialogsettings is an interface that provides persistence for dialog box settings. This interface provides a key-Value Pair storage mechanism. The key must be a string, the value can be a string or a String Array (the method provided by idialogsettings allows the value to be non-string type, but the implementation of idialogsettings converts other basic non-string types to string type and then saves them ). Developers want to save the status when the dialog box is closed. When the dialog box is opened and restored, they can use the idialogsettings interface. The Attachment Program uses inputdialog to save the content entered by the user to the idialogsettings instance. The idialogsettings save method is used to save the information in idialogsettings to the local file. When inputdialog is opened for the second time, use the load method of idialogsettings to load the settings. The code is shown in listing 5.

Listing 4. Use of idialogsettings

Private Static idialogsettings DS = new dialogsettings ("myds"); public static void handleclick () {string filename = "C:/save. XML "; if (new file (filename ). exists () {try {Ds. load (filename) ;}catch (ioexception E1) {e1.printstacktrace () ;}} inputdialog id = new inputdialog (null, "idialogsettings title", "idialogsettings message", DS. get ("iduc") = NULL? "": Ds. get ("iduc"), null); If (ID. open () = Window. OK) {Ds. put ("iduc", id. getvalue ();} Try {Ds. save (filename);} catch (ioexception e) {e. printstacktrace ();}}

 

Enter helloworld in inputdialog and click OK to open the file C:/Save. xml saved in listing 5, as shown in Listing 6. The information in idialogsettings is saved as an XML file by calling the Save method.

Listing 5. Save. XML content

<? XML version = "1.0" encoding = "UTF-8"?> <Section name = "myds"> <item value = "helloworld" Key = "iduc"/> </section>

 

In listing 5, the idialogsettings instance is created by the developer. The save and load operations of the idialogsettings instance must be controlled by the developer. Sometimes, for convenience, we can use the existing idialogsettings instance, let the platform take charge of their reading and writing, such as javaplugin. getdefault (). getdialogsettings () is used to obtain the idialogsettings instance in javaplugin. The loaded and saved files are managed by the Java Plug-in.

Back to Top

Filelocator usage

When editing a project in eclipse, we often create some files in the project as needed, such as the properties file. When we need to find these files during RCP runtime, you need to use the filelocator class. To this end, create a new properties file (filelocator. properties) in the root directory of the project, the content is filelocator = filelocatorusecase. Then, use filelocator to find the property file and read the file content, use the Java resource API to obtain the filelocatorusecase value of filelocator. A dialog box is displayed, as shown in listing 7.

Listing 6. Use of filelocator

URL location = filelocator. find (platform. getbundle ("eclipse_system_class"), new path ("filelocator. properties "), null); propertyresourcebundle bundle = NULL; inputstream is = NULL; string abouttext =" "; if (location! = NULL) {try {is = location. openstream (); bundle = new propertyresourcebundle (is);} catch (ioexception e) {bundle = NULL;} finally {try {If (is! = NULL) is. Close ();} catch (ioexception e) {}} if (bundle! = NULL) {try {// value abouttext = bundle. getstring ("filelocator"); messagedialog. openinformation (null, "filelocator", abouttext);} catch (missingresourceexception e ){}}

 

Use the plug-in ID and the getbundle method of the platform class to obtain the plug-in bundle. The find method of filelocator is relative to the root directory of the bundle to find the file (filelocator. properties), encapsulate the obtained file input stream into propertyresourcebundle, so that you can obtain the filelocatorusecase value based on the key value filelocator.

Back to Top

Workbenchhelp usage

Before learning about workbenchhelp, you need to understand the help expansion points in eclipse. The purpose of this expansion point is to provide developers with methods to customize the Help content, for details about how to use this extension, see the eclipse official development documentation. The workbenchhelp class provides quick APIs for setting, displaying, and obtaining help for help extension points. The attachment program shows how to add help for the composite of the view. When the focus falls on composite, Press F1 to display the defined help content. You can also click "workbenchhelp" to view the Help content. The Result 4 is displayed.

Figure 4. Use workbenchhelp to display help

The code for setting F1 help for view composite is shown in listing 8.

Listing 7. Setting F1 display help

Public void createpartcontrol (composite parent) {composite COM = new composite (parent, SWT. None);... workbenchhelp. sethelp (COM, "eclipse_system_class.contexthelp ");}

 

The sethelp method of workbenchhelp is the control setting help. Its second parameter value is contexthelp in eclipse_system_class.contexthel, which is the Attachment Program extension Org. eclipse. help. contexts extension point defines the context ID. eclipse_system_class indicates the plug-in ID of the Attachment Program. In listing 8, workbenchhelp is used to bind help to composite. When you click F1, the Help content whose ID is contexthelp is displayed. When you try to display help in other events (rather than clicking F1), workbenchhelp provides a method to directly display help: workbenchhelp. displayhelp ("eclipse_system_class.contexthelp"); you can call the displayhelp method in any event listener to display the Help content.

Back to Top

Messagedialogwithtoggle usage

Messagedialogwithtoggle is a prompt dialog box with a checkbox. messagedialogwithtoggle not only saves the user's clicked button information, but also saves whether the user has selected chekbox. Messagedialogwithtoggle has many examples in eclipse. For example, when eclipse is disabled, a dialog box 5 is displayed. This dialog box is the messagedialogwithtoggle instance.

Figure 5. Prompt dialog box when you exit eclipse

The messagedialogwithtoggle Dialog Box applies to the use code of a dialog box that contains two prompts, as shown in listing 9.

Listing 8. Use of messagedialogwithtoggle

Messagedialogwithtoggle dialogwithtoggle = new messagedialogwithtoggle (null, "messagedialogwithtoggle title", null, "messagedialogwithtoggle message", messagedialog. question, new string [] {idialogconstants. yes_label, idialogconstants. no_label}, 0, "Do you want to select Toggle? ", False); If (dialogwithtoggle. open () = idialogconstants. yes_id) {Boolean togglestate = dialogwithtoggle. gettogglestate (); messagedialog. openinformation (null, "messagedialogwithtoggle", "select toggle" + togglestate );}

 

The result of executing the code in listing 9 is 6.

Figure 6. Example of messagedialogwithtoggle

Back to Top

Imemento in viewpart

When the workbench of eclipse is disabled, the savestate method of each view (viewpart) is executed, and an imemento object is passed into the savestate method, the imemento object can store data such as integer, string, and floating point data, so that we can store some status information to imemento. The platform will store the data to Org. eclipse. workbench in the UI metadata directory. XML file. The next time you open the view, the platform will re-read the imemento object from workbench. xml and pass in the init method of the view. Then the init method can restore the status before the last close.

To save the status and restore the status, you need to override the init and savestate methods of the view (viewpart), as shown in listing 10.

Listing 9. init and savestate Rewriting

Public void Init (iviewsite site, imemento memento) throws partinitexception {super. INIT (site, memento); If (memento! = NULL) {string initdata = memento. getstring ("initdata"); // This initdata will be obtained every time you open it .}} public void savestate (imemento memento) {// If the status changes, it will be stored in imemento if (memento! = NULL) {memento. putstring ("initdata", "imemento init ");}}

 

In addition, execute init first when opening the view, and then execute the createpartcontrol method of the view. That is to say, before the init is executed, you can save the reference of the imemento object parameter of the init method, use the createpartcontrol method to obtain the information stored in imemento, so that the attribute values of some previous components can be restored.

Back to Top

Re-recognize the display class

Display plays an important role in RCP. Its Two Methods sync and async are synchronous and asynchronous, and sync puts the code block immediately into the main thread for execution, async is put into the main thread for execution when the main thread is idle. These two methods are widely used when updating the UI in a non-main thread.

There are still many other methods for display to be ignored, but understanding these methods may be of great help in future development,

AddfilterThis method is used to add a global listener. Any similar event in the RCP application will trigger the listener of addfilter.AddfilterAs shown in listing 11.

Listing 10. addfilter example

Display. addfilter (SWT. mousedown, new listener () {@ override public void handleevent (event e) {system. Out. println ("filter mouse down ");}});

 

Display provides a method for finding controls, calledFindwidgetUsed to quickly search for controls through handles. in complex cases, you can call the findwidget method to quickly obtain controls by recording the control's handle number (the control's handle attribute, the sample code is shown in listing 12.

Listing 11. findwidget example

Button displaybtn =... ; Control d = (Control) display. findwidget (displaybtn. Handle); system. Out. println (D = displaybtn );

 

DisplayGetfocuscontrolMethod returns the control object that obtains the focus in the current application.

DisplayTimerexecThe method is used to execute a piece of code after the end of a specified number of milliseconds to provide the scheduled execution function for the RCP program. Its code is shown in listing 13.

Listing 12. Example of timerexec

// Execute the runnable code Display in 5 seconds. timerexec (5000, new runnable () {@ override public void run () {system. out. println ("timerexec ");}});

 

DisplayDisposeexecThe method is the hook when the program exits. It is triggered when the display is destroyed. This method allows you to finish some work when the program exits, as shown in listing 14.

Listing 13. disposeexec example

Display. disposeexec (New runnable () {@ override public void run () {system. Out. println ("disposeexec ");}});

 

Back to Top

Summary

This article introduces several classes that may be used in RCP development. It explains these classes and provides sample code analysis. through the introduction of this article, I believe that readers can learn how to use these classes, get twice the result with half the effort in future RCP development. Due to my limited level of knowledge, if there is any mistake in the article, please contact me for criticism and correction.

Reprinted from:

Http://www.ibm.com/developerworks/cn/opensource/os-cn-ecl-rcpclass/

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.