I use gephi to draw the social graph.But,it use singleton to create class ProjectController.
#ServiceProvider(service = ProjectController.class)
public class ProjectControllerImpl implements ProjectController {
private enum EventType {
INITIALIZE, SELECT, UNSELECT, CLOSE, DISABLE
};
//Data
private final ProjectsImpl projects = new ProjectsImpl();
private final List<WorkspaceListener> listeners;
private WorkspaceImpl temporaryOpeningWorkspace;
public ProjectControllerImpl() {
//Listeners
listeners = new ArrayList<WorkspaceListener>();
listeners.addAll(Lookup.getDefault().lookupAll(WorkspaceListener.class));
registerNetbeansPropertyEditors();
}
And we can get this class through the netbeans api:
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
You can see it has a List in this class.When you create a object from this singleton,it will add the list.It make memory leak,I want to kill the object in org.openide.util.Lookup,how can I do?
The code of the ProjectControllerImpl class you linked to also contains a method removeWorkspaceListener(), which you could use to unregister single listeners when they are not needed any more (assuming you know these listeners and that they can be removed).
You could, of course, use your own ProjectController implementation that handles the listeners in a different way:
You could store instances of WeakReference<WorkspaceListener> instead of strong references to WorkspaceListeners if you do not want your ProjectControllerImpl instance to prevent the WorkspaceListeners to be garbage collected. (This implies that a strong reference to each listener needs to be stored somewhere else as long as the listener instance should live.)
Alternatively, do not store the WorkspaceListeners in your ProjectControllerImpl at all, but fetch them via lookupAll() when you actually need them.
Related
I use Vaadin 14 and would know whether it is possible to report changes in the nested list to objects in the main view.
A rough example is shown in the picture. Above you can see the sum as size (here 2), if I press Delete it should change to 1.
Is that possible and how?
concept
I don't have any code yet, it's a thought where I would like to have a hint about what would be possible, e.g. Observer Pattern or something, but code could look something like this
code:
#Rout("")
public class MainView extends VerticalLayout {
private List<CustomDetails> customDetails = new ArrayList<>();
public MainView(){
final var form = new FormLayout();
customDetails.forEach(form::add);
add(H1("Header"), form)
}
}
public class CustomDetails extends Details{
private CustomForm customForm;
private final Service service;
public CustomDetails(){
customForms = new CustomForm(service.getListOfObjects());
this.setContent(customForms)
}
}
public class CustomForm extend FormLayout{
private FormLayout formLayout = new FormLayout();
private List<Object> objects = new LinkedList<>();
public CustomForm(List<Object> list){
this.objects = list;
setUp();
add(new Paragraph("SUM: "+ list.size()), layout);
}
private void setUp(){
objects.forEarch(o->{
....
layout.add(...)
})
}
}
In Vaadin there is an utility class Binder which is used to bind data to forms. If your use case is related to this, i.e. your so called nested layout is in fact a form and objects you refer to are data beans you want bind into that form. I recommend to study that first.
If you have list editor, I would also investigate if it fits your application to implement it with Grid or IronList/VirtualList, which is backed by DataProvider. Say you edit one item, and after saving the item, you can call dataProvider.refreshItem(item) to update the view.
Observer Pattern or something...
Yes, that is a solution. It is a lot of work and has been done before.
One such library is Beanbag.
Note: I wrote this (or rather, I started writing it a day ago).
EDIT:
As of this edit, we have the ObservableCollection interface. You can use it like so:
// You have a collection called "strings".
// Wrap it in an ObservableCollection.
final ObservableCollection<String, Collection<String>, BasicObservableCollection.Default<String, Collection<String>>> observableStrings = ObservableCollections.observableCollection(strings);
// Add a removed observer.
observableStrings.addElementRemovedObserver(observation -> System.out.println("\"" + observation.getValue() + "\" was removed.");
// Remove an element.
observableStrings.remove("hello");
If you need the wrapper to have List methods, just wait until tomorrow evening EST. I'll have the code up by then and will update this post accordingly.
This question is not manly for Android, but I will use an android example to explain.
I want to create a class that should override the method onTouchListener, to be used on any object that uses those touch methods.
Since after a touch input, the method starts a function, and since it's a class, it can be instantiate several times (and I want to be instantiate several times), I want to prevent that two instances are called at the same time.
I guess I could create a variable inside the class, that assured that if it's true, it can run the method, but I need to check it for all of the class instances.
And since I want to make this a library, I need to do this inside the class itself.
So my question is,
(Java Question) How can I know that a variable from any instance of a class is true?
(Android Question) Or if this is not possible, How can I prevent multiple touch events at the same time?
You could achieve that with static data and/or method for this class. A static element can be accessible from anywhere using the class name:
ex: MyClass.isAlreadyRunning();
you could for example store in an array all the running status of the instances, and create a static method that checks the array if one is already running.
You can think about making a Singleton Class. Wiki Link
Singleton classes allows to create ONLY one instance/object of that class and then reuse it.
You can use a static field in this context. A static field is identicaly for all instances of an class.
You can do it maybe like this:
public Example implements TouchInterface{
private static boolean actuallyRunning = false;
public void touchExecute(){
if(!actuallyRunning){
actuallyRunning = true;
callYourFunction();
actuallyRunning = false;
}
}
}
You can use singleton class if you want one one instance and if you want to handle the multiple touch events
you can disable as soon as your handler start and enable after that.
you can add a time span in normal practice it is one sec but it depends on you handler's complexity
Like this example:
// Make ur activity class to implement View.OnClickListener
public class MenuPricipalScreen extends Activity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
// setup listeners.
findViewById(R.id.imageView2).setOnClickListener(MenuPricipalScreen.this);
findViewById(R.id.imageView3).setOnClickListener(MenuPricipalScreen.this);
....
}
.
.
.
// variable to track event time
private long mLastClickTime = 0;
//View.OnClickListener.onClick method defination
#Override
public void onClick(View v) {
// Preventing multiple clicks, using threshold of 1 second
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
// Handle button clicks
if (v == R.id.imageView2) {
// Do ur stuff.
}
else if (v == R.id.imageView2) {
// Do ur stuff.
}
...
}
.
.`.
You should put "public synchronized" void, so it will prevent to be called in parallel. If you must override, then put a synchronized object in the method so it will do the same.
I am trying to unit test a class which extends org.eclipse.ui.views.properties.tabbed.AbstractPropertySection
It is a GUI on top of a heap of legacy code. The AbstractPropertySection class have a
private TabbedPropertySheetPage tabbedPropertySheetPage;
field, which is initialized by its
public void createControls(Composite parent,
TabbedPropertySheetPage aTabbedPropertySheetPage)
method, and used by its
public TabbedPropertySheetWidgetFactory getWidgetFactory();
method, which in turn used by widget creation. I cannot mock it up in a way that creating a Button would actually create one. As it is both legacy and GUI, maybe it would be wiser to use the Real Thing? But how?
I am doing basically this:
private LineDecorationSection section;
private DiagramConnectionMockup data;
//contains both the model object and editPart
data = new DiagramConnectionMockup();
ConnectionDecorationFactory.getInstance();
//a descendant of the class to be tested,
//augmented with methods to handle what would be done and seen
//on the GUI
section = new LineDecorationSectionExerciser();
assertTrue(section instanceof LineDecorationSection);
//a selection containing theeditPart
ISelection selection = new SelectionMockup(data.getEditPart());
//an editor (Legacy)
IWorkbenchPart editor = new ZentaDiagramEditor();
section.setInput(editor, selection);
//------------This fails-----------
assertNotNull(section.getWidgetFactory());
LineDecorationSectionExerciser exerciser = (LineDecorationSectionExerciser)section;
Button but = ((Button)exerciser.getInternal("DefaultButton"));
//----and this prints "but=null"------------
System.out.println("but="+but);
but.setSelection(true);
The actual code is here: https://github.com/magwas/zenta/blob/001f83c8951a4840b84cd1ff402baa5b96feb4e5/org.rulez.magwas.zenta.editor/src/org/rulez/magwas/zenta/tests/propertysections/LineDecorationSectionTest.java
Question: what to add to the unit tests and mockups so that the unit tests run, and widgets get created?
In the end I have come up with real underlying data and mockups for the Property Sheet page and the goo coming with it. Maybe not the best solution, but I have put the mockup initialisation into the exerciser class.
The solution for the real-world problem is here:
https://github.com/magwas/zenta/blob/51fd9f6b9e363eb5967a3d24b22d012b5bdd6492/org.rulez.magwas.zenta.editor/src/org/rulez/magwas/zenta/tests/propertysections/LineDecorationSectionTest.java
I am developping a server application in Java. I need to load some ressources from different sources (XML and a Database). So, i need some advice on how to cleanly implement the loading.
I have a class "ServerX" who create some "Memory" object, it's those objets who'll hold the loaded ressources.
I've found two different way of loading, but both seems dirty.
1
public class ServerX
{
/**
Will hold the houses for further use.
*/
private Memory<House> houses;
public ServerX()
{
houses = new Memory<House>();
loadHouses();
loadXX();
loadYY();
LoadZZ();
Load...
}
private void loadHouses()
{
//Pseudo code
List<House> loaded = loadHousesFromDatabase();
houses.addAll(loaded);
}
private void loadXX();
...
}
But this way, it flood my "ServerX" class.
2
public interface Loader
{
public void loadHouses(Memory<House> toFill);
public void loadXX(Memort<XX> toFill);
public void loadYY(Memort<YY> toFill);
public void loadZZ(Memort<ZZ> toFill);
}
public class SimpleLoader implements Loader
{
//Implements methods.
}
public class ServerX
{
/**
Will hold the houses for further use.
*/
private Memory<House> houses;
public ServerX(Loader loader)
{
houses = new Memory<House>();
loader.loadHouses(houses);
loader.loadXX...
}
}
But this way, i think i fall into the Poltergeist antipattern, because i create a new loader only to do the request to the database/XML file, and then it's garbage-collected.
So, is there another way to do it, or is one of my solutions good enough?
Thanks.
One pattern you can consider is the Service Locator Pattern. An explanation of Service Locator can be found here.
Basically, a service locator is a registry + cache combined to find the resource once and keep it in memory for object retrieval during the lifecycle of the application. Service Locator is mainly implemented using the Singleton pattern.
Your second solution using a Loader interface and multiple implementations (XMLLoader and DBLoader) is good. However, keep the loader and the server decoupled by making the load methods return a new Memory instance instead of passing the memory as a reference. Add a copyAll method in Memory class to copy the contents of one memory into another memory. ( See ArrayList.addAll or System.arrayCopy in javadoc )
I've problem regarding GUI with one Menu and one Order Class.
I've created a variable to store how many items have been selected in the Menu Class.
private int totalSelected;
The var totalSelected is live updated. It can be changed anytime depending on actionPerformed() function.(Exp: totalSelected will add up all the selected items)
In the Order Class, how can I access to the live update variable totalSelected in order to retrieve the live update value? When I invoke getTotalSelected() function inside the Menu Class, I will only obtain a 0 value.
Thanks for your help ^^!
Please allow me to specify my question clearer.
public class MenuTab extends JPanel
{
private JLabel display;
private int totalSelected;
public MenuTab()
{
....
}
}
public getTotalSelected(){
return totalSelected;
}
private class SelectedListener implements ActionListener
{
public void actionPerformed()
{
.......
//Assume that totalSelected has been updated!
display = new JLabel("Total: " + totalSelected);
// OK to display totalSelected live value here.
}
}
// A new class is the confirmation of order
public class OrderConfirmedTab extends JPanel{
private JLabel displayTotal;
private MenuTab order = new MenuTab();
public OrderConfirmedTab()
{
......
int totalSelected = order.getTotalSelected();
displayTotal = new JLabel("Total: " + totalSelected);
// Problem to display totalSelected live value here.
// Will obtain 0;
// How can I obtain the live updated value from class MenuTab? Thanks!
}
}
If I read your code right, you need to make your variable be private static int totalSelected; You need to make it static so that it stays the same for all instances of the class.
I looks like your not updating the private int totalSelected; variable when a user makes a selection, so it is always 0.
Ya! I just realized that my JLabel
will not update the value
automatically. So how can I fix it?
Thanks! – Christine
If I understand you correctly you have two GUIs where changes in one (the MenuTab) will update the other (OrderConfirmedTab) in real time?
If so, you will need to increase the coupling between the two objects. If MenuTab has a reference back to OrderConfirmedTab then it can call methods to update the value as it changes.
For example, pass OrderConfirmedTab into MenuTabs constructor
MenuTab mt = new MenuTab(this); // from within OrderConfirmTabs costructor
Then when MenuTab has an actionPerformed event it can call back to OrderConfirmTab
orderConfirmTab.setTotalSelected(totalSelected); // you have to create this method in OrderConfirmTab
I hope this helps a little
You can use PropertyChangeListener and PropertyChangeSupport mechanisms to dispatch an event when the value is updated and to be notified when the variable has changed. Your JLabel is not going to update on its own; even if you were to use an object other than a primitive (note that primitives are merely values, while objects are actually implicit pointers); you will need to update your JLabel when the variable changes, since the JLabel simply stores a string, not a reference to the variables from which the string was constructed.
This is the concept of model-view-controller; your variable should be in some sort of class or classes that represent the model (the information) and which allow changes to be observed via property change events. Your view classes should simply provide display logic and no business or application-specific logic. It is the controller in which your application logic should reside; your controller should register for events on the model, and it should update the view whenever the model has changed, and it should likewise update the model when the view dispatches events that should result in the model being changed.