Eclipse RCP proporciona una forma sencilla de crear aplicaciones de escritorio con estándares de la industria. Una vez que comprenda cómo funciona el marco, es muy sencillo agregar más vistas, perspectivas, etc.
Este artículo muestra cómo crear una aplicación de cliente enriquecido simple con una vista utilizando el asistente de desarrollo. También explica la función de cada archivo creado. Supongo que ya tiene PDE instalado. Si no lo hace, puede averiguar rápidamente cómo hacerlo en el tutorial «Cómo instalar PDE».
1. Pasos para crear una aplicación RCP simple con una vista
Las siguientes 4 imágenes muestran los 4 pasos para crear una aplicación simple con asistente.
La plantilla utilizada es «Aplicación RCP con vista».
2. Archivos creados y sus funciones
Aquí están los archivos creados automáticamente por Eclipse.
Eclipse RCP proporciona el concepto de «puntos de extensión» y «extensiones» para facilitar el desarrollo de aplicaciones de escritorio comerciales. Proporciona una forma de usar todo el marco fácilmente a través del archivo plugin.xml que se encuentra en el directorio raíz de cada directorio.
plugin.xml
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> <extension id="application" point="org.eclipse.core.runtime.applications"> <application> <run class="rcpview.Application"> </run> </application> </extension> <extension point="org.eclipse.ui.perspectives"> <perspective name="Perspective" class="rcpview.Perspective" id="RCPView.perspective"> </perspective> </extension> <extension point="org.eclipse.ui.views"> <view name="View" class="rcpview.View" id="RCPView.view"> </view> </extension> <extension point="org.eclipse.ui.perspectiveExtensions"> <perspectiveExtension targetID="*"> <view standalone="true" minimized="false" relative="org.eclipse.ui.editorss" relationship="left" id="RCPView.view"> </view> </perspectiveExtension> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="menu:org.eclipse.ui.main.menu"> <menu label="File"> <command commandId="org.eclipse.ui.file.exit" label="Exit"> </command> </menu> </menuContribution> </extension> </plugin> |
Durante el inicio de una aplicación Eclipse RCP, el tiempo de ejecución de Eclipse detecta la clase de punto de entrada principal a través del punto de extensión definido en plugin.xml. La clase implementa la interfaz IApplication y se carga primero como la función principal en una aplicación Java general.
Application.java
package rcpview; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; /** * This class controls all aspects of the application's execution */ public class Application implements IApplication { public Object start(IApplicationContext context) { Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } return IApplication.EXIT_OK; } finally { display.dispose(); } } public void stop() { if (!PlatformUI.isWorkbenchRunning()) return; final IWorkbench workbench = PlatformUI.getWorkbench(); final Display display = workbench.getDisplay(); display.syncExec(new Runnable() { public void run() { if (!display.isDisposed()) workbench.close(); } }); } } |
La clase de aplicación crea y ejecuta un Workbench.
¿Qué es un banco de trabajo?
Workbench se basa en Runtime, SWT y JFace para proporcionar un entorno de múltiples ventanas altamente escalable y abierto para administrar vistas, editores, perspectivas (diseños orientados a tareas), acciones, asistentes, páginas de preferencias y más.
Workbench se configura a través de WorkbenchAdvisor. WorkbenchAdvisor le dice a Workbench cómo comportarse, cómo dibujar, qué dibujar, etc. En particular, WorkbenchAdvisor identifica dos cosas (verifique el código a continuación):
1. La perspectiva inicial que se va a mostrar.
2. qué WorkbenchWindowAdvisor utilizar.
ApplicationWorkbenchAdvisor.java
package rcpview; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { private static final String PERSPECTIVE_ID = "RCPView.perspective"; public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public String getInitialWindowPerspectiveId() { return PERSPECTIVE_ID; } } |
El banco de trabajo inicia WorkbenchWindow, que se configura a través de WorkbenchWindowAdvisor.
ApplicationWorkbenchWindowAdvisor.java
package rcpview; import org.eclipse.swt.graphics.Point; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { super(configurer); } public ActionBarAdvisor createActionBarAdvisor( IActionBarConfigurer configurer) { return new ApplicationActionBarAdvisor(configurer); } //preWindowOpen method configure the initial window size and positions. public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); configurer.setInitialSize(new Point(400, 300)); configurer.setShowCoolBar(false); configurer.setShowStatusLine(false); configurer.setTitle("RCP Application"); } } |
WorkbenchWindowAdvisor crea la barra de herramientas / barra de menú de la aplicación que se configura a través de ActionBarAdvisor. La clase ApplicationActionBarAdvisor a continuación es demasiado simple para implementar cualquier método. Pero generalmente, los siguientes dos métodos se pueden usar para llenar la barra de menú y la barra de herramientas:
protected void fillMenuBar(IMenuManager menuBar) { } protected void fillCoolBar(ICoolBarManager coolBar) { } |
ApplicationActionBarAdvisor.java
package rcpview; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; /** * An action bar advisor is responsible for creating, adding, and disposing of * the actions added to a workbench window. Each window will be populated with * new actions. */ public class ApplicationActionBarAdvisor extends ActionBarAdvisor { // Actions - important to allocate these only in makeActions, and then use // them // in the fill methods. This ensures that the actions aren't recreated // when fillActionBars is called with FILL_PROXY. public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } } |
En una aplicación típica, cuando la inicia, aparece una ventana. La perspectiva es como la página de un libro, mientras que el libro es la ventana. Una perspectiva es un contenedor de elementos visuales como vistas, editores y acciones. Cada perspectiva puede contener 0 o varias vistas según el diseño.
Perspective.java
package rcpview; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(false); layout.setFixed(true); } } |
Una vista es una parte del banco de trabajo para realizar una tarea visual, como navegar por un directorio de árbol, editar un correo electrónico, etc. Proporciona una mejor manera de organizar los componentes visuales en función de sus funciones o propósitos.
View.java
package rcpview; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; public class View extends ViewPart { public static final String ID = "RCPView.view"; private TableViewer viewer; /** * The content provider class is responsible for providing objects to the * view. It can wrap existing objects in adapters or simply return objects * as-is. These objects may be sensitive to the current input of the view, * or ignore it and always show the same content (like Task List, for * example). */ class ViewContentProvider implements IStructuredContentProvider { public void inputChanged(Viewer v, Object oldInput, Object newInput) { } public void dispose() { } public Object[] getElements(Object parent) { if (parent instanceof Object[]) { return (Object[]) parent; } return new Object[0]; } } class ViewLabelProvider extends LabelProvider implements ITableLabelProvider { public String getColumnText(Object obj, int index) { return getText(obj); } public Image getColumnImage(Object obj, int index) { return getImage(obj); } public Image getImage(Object obj) { return PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_OBJ_ELEMENT); } } /** * This is a callback that will allow us to create the viewer and initialize * it. */ public void createPartControl(Composite parent) { viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new ViewContentProvider()); viewer.setLabelProvider(new ViewLabelProvider()); // Provide the input to the ContentProvider viewer.setInput(new String[] {"One", "Two", "Three"}); } /** * Passing the focus request to the viewer's control. */ public void setFocus() { viewer.getControl().setFocus(); } } |
Haga clic en Tutoriales de desarrollo de Eclipse RCP para ver temas más avanzados.