Open main menu

CDOT Wiki β

Changes

Teams Winter 2011/team1/RCP/Create RPC Application

4,645 bytes removed, 13:55, 9 March 2011
Create a RCP Application
=== 1. Create project and data model a RCP Application ==='''This tutorial uses the [http://www.vogella.de/articles/EclipseJFaceTable/article.html#jfaceviewers Jface Tutorial] as reference.''' <br/>In this tutorial we are going to demonstrate how to build a simple RCP application to maintain student's information. We keep the data in a List object and will not preserve data. <br/>
To begin with, we create a simple RCP from the "Hello World" RCP template. The will add our Model classes. Eventually we use perspective, view, Jface viewe and Commands, to display, edit, Add and Delete students' records.<br/>=== 2. Show Data in = Start The Application ====2.1 Columns data in Create a JFace table can be hold new plug-in <codeproject from File menu (File>New>ModelProvider</codeProject> and it is defined via instances of <codePlug-in Development>TableViewerColumnPlug-in project).<br/code> object[[Image:createRCPApp1.jpg | 400px]]<br/> <codebr/>viewerName it: "cs.setInput(ModelProviderecl.INSTANCErcp.getStudents());</code>SimpleRCP"<br/>and <code>TableViewerColumn col = createTableViewerColumn(titles[0[Image: createRCPApp2.jpg | 400px], bounds[0], 0);<br/code>2.2 Add the following lines to <code>StudentsView.java<br/code> classSelect "Yes" in responce to the question:" Would you like to create a rich client application?"<br/>Private variable[[Image: createRCPApp3.jpg | 400px]]<br/><code>private TableViewer viewer;<br/code>Select the "Hello RCP" in the Templates screen.<br/>Change the <code>createColumns()method[[Image:createRCPApp4.jpg | 400px]]<br/> <prebr/> String[] titles = { Un-check "IdAdd branding", "First name", "Last name", "Program" };.<br/> int[] bounds = { 100, 100, 100, 100 }; // First column is for the student id TableViewerColumn col = createTableViewerColumn(titles[0Image: createRCPApp5.jpg | 400px], bounds[0], 0); col.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { Student s = (Student) element; return s.getId(); } }); <br/pre><br/>Add The "RCP" project is created with some classes already in it. We will modify this project to create our RCP application for the same functionality for other three columns2purpose if this tutorial.3 Run your application:<br/>[[Image: Create1createRCPApp6.png jpg | 400px700px]]<br/><br/>In the "ApplicationWorkbenchWindowAdvisor" class, modify the preWindoOpen() method to set the title of the window ar "Simple RCP Application".<br/><code>ApplicationWorkbenchWindowAdvisor.java </code> to <code> true</code><source lang=java>
public void preWindowOpen() { IWorkbenchWindowConfigurer configurer === 3getWindowConfigurer(); configurer. Add Edit Cell Data Option ===setInitialSize(new Point(400, 300));3 configurer.1 To make the column editable you need to define an object of type <code>EditingSupport/<code> on your TableColumnViewersetShowCoolBar(false); configurer.setShowStatusLine(false);3 configurer.2 Create new class for each column that extends <code>EditingSupport<setTitle("Simple RCP Application"); //code> class:$NON-NLS-1$ <pre> configurer.setShowStatusLine(true); package cs configurer.ecl.rcp.simplercp.editsetShowPerspectiveBar(true); }</source>
import org==== Run The Application ====To run the application, right click on the project and select :Run As> Eclipse Application.eclipseAlternatively, you can click on the "Run an Eclipse Application" In the "Testing section of the project Overview window.jface<br/>[[Image: RCPRun1.viewers.CellEditor;jpg | 700px]]<br/><br/> import org.eclipse.jface.viewers.EditingSupport;At this point, the application starts and looks like this:<br/> import org.eclipse.jface[[Image: RCPRun2.viewers.TableViewer;jpg | 350px]]<br/> import org.eclipse.jface.viewers.TextCellEditor;<br/> '''Run Configuration'''<br/> import cs.ecl.rcp.simplercpYou can also set the run configuration if required, for example if there is a separate project for a view and you want to add that view to the perspective of the current project you need to make sure that both projects are running, so you need to set that in the run configuration, and you can reach it by right clicking on the project in Project explorer view and select Run As> Run configuration, and double clicking on the '''Eclipse Application''' to create a new Run configuration for the application.modelHowever, for this project we do not need any new run configuration.Student;<br/>
public === Add Model ===In order to have a data model for Student, we need to create a "Student Class" which keeps an student's data and "ModelProvider" Class that creates and keeps a list of Student class IdEditingSupport extends EditingSupport {objects.<br/>private final TableViewer viewer;==== Create Model Package ====Create a package named "cs.ecl.rcp.simplercp.model" in the src directory of your project.<br/>==== Add Model Class(s) ====Add a class named "Student" in the above package.Add the student related fields and make sure that the class uses "PropertyChangeSupport" and "PropertyChangeListener" when setting the properties. For this purpose we need to have an instance of the "PropertyChangeSupport" class to be build by passing the Student object(this) to it, and implement the metods:"addPropertyChangeListener" and "removePropertyChangeListener". The following code demonstrates how to create the Student Model and how to add Property Change Support to the class.
public IdEditingSupport(TableViewer viewer) { super(viewer); this<code>Student.viewer = viewer; }java </code>
@Override protected CellEditor getCellEditor(Object element) { return new TextCellEditor(viewer.getTable()); }<source lang=java>
@Override protected boolean canEdit(Object element) { return truepackage cs.ecl.rcp.simplercp.model; }
@Overrideimport java.beans.PropertyChangeListener; protected Object getValue(Object element) { return ((Student) element)import java.beans.getId()PropertyChangeSupport; }
@Overridepublic class Student { protected void setValue private String id; private String firstName; private String lastName; private String program; private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public Student(){ } public Student(Object elementString id, String firstName, String lastName, Object valueString program) { super((Student) element); this.setId(Stringid= id; this.valueOf(value))firstName= firstName; viewer this.refresh()lastName= lastName; } this.program= program; }</pre><br/> 3.3 Assign <code>EditorSupport</code> objects to your <code>TableColumnViewers </code>in your <code>StudentView</code> class.<br/> Add the following line at the end of the <code>LabelProvider</code> is set:<br/> public void addPropertyChangeListener(String propertyName,PropertyChangeListener listener) { <code>col propertyChangeSupport.setEditingSupportaddPropertyChangeListener(new IdEditingSupportpropertyName, listener); } public void removePropertyChangeListener(viewerPropertyChangeListener listener){ propertyChangeSupport.removePropertyChangeListener(listener);</code><br/>3.4 Run your application. You should now be able to modify the content of the table:<br/>[[Image: Create2.png | 400px]]<br/> }
=== 4. Add Sorting Option === public String getId() {4.1 Create a new Class <code>StudentViewerComparator.java</code> put it in package <code>sorter</code>:<br/> return id; <pre> package cs.ecl.rcp.simplercp.sorter; }
import org.eclipse.jface.viewers.Viewer public String getFirstName() { return firstName; import org.eclipse.jface.viewers.ViewerComparator; }
import cs.ecl.rcp.simplercp.model.* public String getLastName() { return lastName; }
public class StudentViewerComparator extends ViewerComparator String getProgram() { private int propertyIndex return program; private static final int DESCENDING = 1; private int direction = DESCENDING; }
public StudentViewerComparatorvoid setId(String id) { propertyChangeSupport.firePropertyChange("id", this.id, this.propertyIndex id = 0id); } public void setFirstName(String firstName) { direction propertyChangeSupport.firePropertyChange("firstName", this.firstName, this.firstName = DESCENDINGfirstName); } public void setColumnsetLastName(int columnString lastName) { if propertyChangeSupport.firePropertyChange(column == "lastName", this.propertyIndex) {lastName, // Same column as last sort; toggle the direction direction this.lastName = 1 - directionlastName); } else public void setProgram(String program) { // New column; do an ascending sort propertyChangeSupport.firePropertyChange("program", this.program, this.propertyIndex program = columnprogram); direction = DESCENDING } public String toString() { return id +" "+firstName + " " + lastName + " "+ program ; } }
@Override public int compare(Viewer viewer, Object e1, Object e2) { Student s1 = (Student) e1; Student s2 = (Student) e2; int rc = 0; switch (propertyIndex) { case 0: rc = s1.getId().compareTo(s2.getId()); break; case 1: rc = s1.getFirstName().compareTo(s2.getFirstName()); break; case 2: rc = s1.getLastName().compareTo(s2.getLastName()); break; case 3: rc = s1.getProgram().compareTo(s2.getProgram()); break; default: rc = 0; } // If descending order, flip the direction if (direction == DESCENDING) { rc = -rc; } return rc; } } </pre><br/>4.2 Add new private variable to <code>StudentsView</code> class:<br/><code>private StudentViewerComparator comparator;</code><br/>4.3 Add the following lines to the end of <code>createPartControl()</code> method:<br/> <pre> comparator = new StudentViewerComparator(); viewer.setComparator(comparator); </pre><br/>4.4 Add <code>SelectionListener</code> the to the <code>createTableViewerColumn()</code> method: <code>column.addSelectionListener(getSelectionAdapter(column, colNumber));</code><br/>4.5 Add new method:<br/> <pre> private SelectionAdapter getSelectionAdapter(final TableColumn column, final int index) { SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { comparator.setColumn(index); int dir = viewer.getTable().getSortDirection(); if (viewer.getTable().getSortColumn() == column) { dir = dir == SWT.UP ? SWT.DOWN : SWT.UP; } else { dir = SWT.DOWN; } viewer.getTable().setSortDirection(dir); viewer.getTable().setSortColumn(column); viewer.refresh(); } }; return selectionAdapter; }</pre><br/>4.6 Run the application. Click on a column header, the table should be sorted according to the content of this column.<br/>There will also appear a sort-direction in the top of the column:<br/>[[Image: Create3.png | 400px]]<br/source>
=== 5. = Add Filter(Search) Option Model Provider ====5"ModelProvider" class creates and maintains an ArrayList of Student objects and helps us find an student by it's id from the list of students.1 Create new class that extends <codebr/>ViewerFilter</code>:ModelProvider.java <br/code> <pre> package cs.ecl.rcp.simplercp.filter;
import org.eclipse.jface.viewers.Viewer;<source lang=java> import orgpackage cs.eclipseecl.jfacercp.viewerssimplercp.ViewerFiltermodel;
import csjava.eclutil.rcp.simplercpArrayList;import java.modelutil.*List;
public class StudentFilter extends ViewerFilter enum ModelProvider { private String searchStringINSTANCE;
public void setSearchTextprivate List<Student> students; private ModelProvider(String s) { students = new ArrayList<Student>(); // Search must Data could be a substring of the existing valueretrieved here from database students.add(new Student("01234567","Ladan", "Zahiroleslam", "CPA")); thisstudents.searchString = add(new Student("09876543", "Anastasia", "Semionova", "CPA")); students.*add(new Student(" + s + 01122334", "Minoo", "Ziaei", "CPA")); students.*add(new Student("02233445", "Sergiu", "Ecob", "CPA"));
}
@Override public boolean selectStudent getPersonById(Viewer viewer, Object parentElement, Object elementString id) { for (Student student : students) { if (searchString == null || searchStringstudent.lengthgetId() == 0id) { return truestudent; }
}
Student s = (Student) element; if (s.getFirstName().toLowerCase().matches(searchString.toLowerCase())) { return true; } if (s.getLastName().toLowerCase().matches(searchString.toLowerCase())) { return true; } if (s.getProgram().toLowerCase().matches(searchString.toLowerCase())) { return true; } if (s.getId().matches(searchString)) { return true; }  return falsenull;
}
}
</pre><br/>
5.2 Create a new private variable in the <code>StudentView</code> class:
<code>private StudentFilter filter;</code><br/>
5.3 Add the filter to <code>createPartControl()</code> method:<br/>
<pre>
filter = new StudentFilter();
viewer.addFilter(filter);
</pre><br/>
5.4 Run the application. Search for the student:<br/>
[[Image: Create4.png | 400px]]<br/>
 
=== 6. Add Highlights to Search ===
6.1 Create a new helper class and put it in <code>util</code> package. <br/>
Method in this class use logic that is case-insensitive, because filter is case-insensitive:<br/>
<pre>
package cs.ecl.rcp.simplercp.util;
import java.util.ArrayList; import java.util.List;  public class SearchUtil { public static int[] getSearchTermOccurrences(final String searchTerm, final String content) { if (searchTerm == null || searchTerm.length() == 0) { return new int[0]; } if (content == null) { throw new IllegalArgumentException("content is null"); } final List<Integer> list = new ArrayList<IntegerStudent>getStudents(); int searchTermLength = searchTerm.length(); int index; int fromIndex = 0; int lastIndex = -1; int lastLength = 0; while (true) { index = content.toLowerCase().indexOf(searchTerm.toLowerCase(), fromIndex); if (index == -1) { // no occurrence of "searchTerm" in "content" starting from // index "fromIndex" if (lastIndex != -1) { // but there was a previous occurrence list.add(Integer.valueOf(lastIndex)); list.add(Integer.valueOf(lastLength)); } break; } if (lastIndex == -1) { // the first occurrence of "searchTerm" in "content" lastIndex = index; lastLength = searchTermLength; } else { if (lastIndex + lastLength == index) { // the current occurrence is right after the previous // occurrence lastLength += searchTermLength; } else { // there is at least one character between the current // occurrence and the previous one list.add(Integer.valueOf(lastIndex)); list.add(Integer.valueOf(lastLength)); lastIndex = index; lastLength = searchTermLength; } } fromIndex = index + searchTermLength; } final int n = list.size(); final int[] result = new int[n]; for (int i = 0; i != n; i++) { result[i] = list.get(i); } return resultstudents;
}
}
</pre><br/>
6.2 Change the way columns are created in the <code>createColumns()</code> method.<br/>
Following is the code for the first column, other columns need to be changed in similar way:<br/>
<pre>
// First column is for the id
TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0);
col.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
String search = searchText.getText();
Student student = (Student) cell.getElement();
String cellText = student.getId();
cell.setText(cellText);
if (search != null && search.length() > 0) {
int intRangesCorrectSize[] = SearchUtil
.getSearchTermOccurrences(search, cellText);
List<StyleRange> styleRange = new ArrayList<StyleRange>();
for (int i = 0; i < intRangesCorrectSize.length / 2; i++) {
int start = intRangesCorrectSize[i];
int length = intRangesCorrectSize[++i];
StyleRange myStyledRange = new StyleRange(start,
length, null, colorYellow);
styleRange.add(myStyledRange); } cell.setStyleRanges(styleRange .toArray(new StyleRange[styleRange.size()])); } else { cell.setStyleRanges(null); }
super.update(cell); setStatusLine("Student search has been updated"); } }); col.setEditingSupport(new IdEditingSupport(viewer)); </presource><br/>6.3 Run the application. Now your search matches are highlighted:<br[[Teams_Winter_2011/>team1| Index Page]] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [[Image: Create5.png Teams_Winter_2011/team1/RCP/Define_and_use_commands| 400pxNext>>]]
1
edit