Monday, August 6, 2007

Eclipse RCP Views - How to communicate between them

When I was starting out my Eclispe program life, which was not very long ago, I had quite the dilemna of how in the hell would I have ViewOne communicate with ViewTwo, three and four. After talking to a good friend of mine he introduced me to an old idea that still works great. Use a class called ApplicationSingleton. This class is really very handy and I thought I'd talk about it here with a simple example.



public class ApplicationSingleton {
static private ApplicationSingleton instance;
private ItagTreeView.TreeParent chart;

public static ApplicationSingleton getInstance() {
if (instance == null) {
instance = new ApplicationSingleton();
}
return instance;
}
private ApplicationSingleton() {
super();
}
public void SetCurrentChart(ItagTreeView.TreeParent tp) {
chart = tp;
}
public ItagTreeView.TreeParent getCurrentChart() {
return chart;
}
}



Now to talk about some parts of this class.

  1. We include a private variable of our class called "instance"
  2. From our application code we make calls to getInstance(), such as this:
    TreeParent tp = ApplicationSingleton.getInstance().GetCurrentChart(); The first time we call getInstance it will make an instance of this class.
  3. By using setCurrentChart() we can store our variables in view1 and in view2 we can use getCurrentChart.
Using this method allowed me to have two distinct view communicate. One view was my ChartView and the other was my FormView. I also tied in a TreeView so when a user double clicks a chart node it grabs the data for that node and displays a chart and resets the form view for the given chart.

Easy, right? :) If you have any questions or comments I'd love to hear them!

No comments: