Java : reference one form from another form to append values - java

In my application I have a main form which has buttons to process other actions, for example my main form displays a list of all entities in my system, and a user is then able to select and then Add or Edit those entities in the application.
When a user presses "Add" a new JFrame is opened, allowing them to add to the system. This is all fine, however I am having a small problem which is affecting some functionality.
I wrote a CommandTracker which allows me to undo and redo operations, the library works fine however I am struggling to reference the CommandTracker object on my main form from other forms. (hopefully code shall convey my question better)
Main Form Declarations:
protected CommandTracker;
// This is instantiated in my constructor, trying to show less code to keep simple.
objCommandTracker = new CommandTracker();
This instantiates my new Command Tracker object within my main form, I would then like to reference this object from my subform so that I can append the next command fired in my sub form.
So far I have tried to resolve this by providing a reference to my main form within my subforms .java file
protected static MainMenu main_menu = null;
I then tried to access the command tracker as follows
// Run AddRequestCommand, through the command tracker
mainMenu.objCommandTracker.executeCommand(addCommand);
However, this results in a null pointer Exception being thrown, I assume this is because mainMenu has a null reference in its declaration. How do I go about passing the current active MainMenu instance to my subform?

Use of statics is never the way to solve something like this. The solution is to pass valid references where needed and to call appropriate methods on these references.
So in other words, if one class needs reference to another, then pass the reference in via a parameter, either a constructor parameter or a setter method parameter, use it to set a field, and then you are free to call methods on that reference in that class.
As an aside: at some other time we'll need to discuss the problems with shooting multiple JFrames at the user, and at your atypical use of the term "form" as if it had a standard meaning in the Swing library -- it doesn't, and so you'll want to use other clearer terms.

Related

Is it possible to make a static reference to an excel sheet in AnyLogic?

I want to call an Excel with a static java function within an AnyLogic Model as shown in the picture. The function "readExcelFile" has to be static, because I want to call it from another class within my AnyLogic Project.
However, when I call the function, an error occurs: "Cannot make a static reference to the non-static field produktionssystem".
Is there a solution for this problem?
The error is because the Excel element produktionssystem can only ever be a (non-static) element in whatever agent type your function is also in (Main from the screenshot). By definition a static function cannot see any elements (Java fields) inside agent instances.
But you should never need a static function unless you need to share it across runs (which can have dangerous side effects if you're not careful). Your agents that need to call it just need a reference to an agent instance that does have the function.
If the calling agent is a 'child' of the function-declaring agent, you've already got the "Link to upper level agent" main provided by AnyLogic (and this will always exist if the calling agent is anywhere in the model's hierarchy of agents). Otherwise your calling agent will need something like a parameter of type Main which is set by whoever creates it.
It's tough to understand what is causing the error here, because I can't see inside your function.
There is no inherent issue with read/write to Excel files from within another class (i.e. within another agent, custom class, etc...).
Here is a link to a public model on the AnyLogic cloud that I found very helpful when I first started working with Excel files within AnyLogic:
https://cloud.anylogic.com/model/99d9f196-17e7-47c3-9b28-63a6f23b0dad?mode=SETTINGS

Updating form elements with ActionListener from loaded objects

I have a form with some checkboxes and spinners. They all have ActionListeners\ChangeListeners assigned to them, so each time you change some element, the program launches a create() method, which gathers all the values from the entire form and puts them into object, which can be saved to disc later.
But now I'm trying to make the program to load that object from file and update the interface according to what has been loaded. This is where problems arise. After the program has loaded the object, it tries to update the elements of the form, but just as it changes the first one, ActionListener is triggered and it gathers all the values from the form and overwrites the object that was loaded before.
What would be a good way to solve this problem?
Right now I'm thinking about creating a global variable to "switch off" the create() method when I load the object (that is to create a flag that stops action listeners). But I'm not sure if this is a good idea.
Instead of flag maybe think of creating an enumeration called FormState to represent states of the form e.g. READ and EDIT. You can toggle the state of the form before and after persisting values.
Solved it by adding a private boolean variable which is changed to false when interface is being updated.

Is it safe to hold on to a mapped TestObject in RFT?

Mapped TestObjects are generally accessed through getter methods, e.g.
button().click();
// Other code
button().click();
// ...
button().click();
Is there any reason why I shouldn't retrieve the TestObject once and reuse it? E.g.
GuiTestObject button = button();
button.click();
button.click();
button.click();
Or, stated differently, is there any reason why RFT generates getter methods instead of member variables?
The only potential reason I can think of would be to avoid tying up the application under test's memory, but that doesn't make any sense to me; Java finalizers aren't reliable so I doubt RFT is freeing up any resources when the TestObject is garbage collected. Plus, the fact that I can keep using the same mapped TestObject even if I close and re-open the application suggests RFT is re-finding (and subsequently unregistering) the test object every time I try to use it.
If there's no downside, why does every reference I find access TestObjects through getter methods exclusively? E.g. An Object-Oriented framework for IBM RFT, listings 2 and 3.
I think, first its because
button().click();
is cleaner/simpler code to a user than ..
GuiTestObject button = new GuiTestObject( getMappedTestObject("thebutton"));//This currently resides in the helper file.
button.click();
Second, the button() method can be passed an "Anchor" and a "Flag" also which is again implemented in the Helper class.so again
button(anchorobject,flags).click();
is simpler than having, one more button object
GuiTestObject button1 = new GuiTestObject(getMappedTestObject("thebutton"),anchor,flags);
button1.click();
In case you mean having something like..
GuiTestObject button = button();//where button() still is in helper class
button.click();
button.dosomthingelse();
Then we would need to specify the actual type of object for the button then we have a different TestObject type for Text controls and selects and trees etc.
With this existing approach the user can be completely unaware of existence of different types of TestObjects (GuiTestObject / TextGuiTestObject/SelectGuiSubitemTestObject) etc which is returned by the getter method of an object.
What we are dealing with in the script is a TestObject which resides in the playback process. TestObject is just a specification to find an actual object in the application and create a proxy for it (which resides in the application process) , and this proxy is what gets released once a particular action completes (click() for instance). However the TestObject is still valid , and as you have rightly said RFT would again find the object if you reuse the testobject. TestObject would be taken care of by the Garbage collector as and when required, user can further optimize that code I guess.
Finally to answer your question I am not aware what would be the downside of using the testobject you have. I don't think it will help you in terms of performance also though.
Try timing how much time it saves you if any by using an Object instead of the getter , try it on Java application which is statically enabled.

JPanel with anonymous EventListener - why doesn't GC destroy listener?

I have been perusing the open source code of JMapViewer. If anyone else wishes to look at it, check the SVN.
In a nutshell, the main class is JMapViewer, which is an extension of a JPanel. There is another very important class called DefaultMapController which acts as a MouseListener for the main class.
The first weird thing I noticed is that the viewer has no references to the controller. The JMapViewer constructor instantiates an anonymous instance of the DefaultMapController, like this:
public JMapViewer() {
// other stuff
new DefaultMapController(this);
}
This seems to me to be a poor design choice, since the controller has tons of methods (options, toggles, etc - example shown below), which now can not be accessed at all, so what good are they?
public void setMovementMouseButton(int movementMouseButton) {
// changes which mouse button is used to move the map
}
The controller does have a reference to the viewer as shown in the first snippet above, which is how it is able to exercise control.
However, then I thought of something even weirder! If this anonymous instance of the listener has no references, why is it allowed to even survive? Shouldn't the GC destroy it quickly? Or is GC smart enough to know that a listener class which references a live JComponent must also stay alive to work properly, even if it has no name for some strange reason?
So, two real questions:
why does GC not destroy object?
is this indeed a poor design choice, or is there some way I'm unaware of to access the controller from the class which instantiates the viewer?
I want to contribute to this open source library, and my first idea for a change is to change the JMapViewer class to have a field referencing its controller, and to change the constructor to assign the currently anonymous controller to this new field. But, I want to make sure I'm not ignorantly missing something. I have searched the entire codebase for the text DefaultMapController, and it only occurs in its own class definitions, and in the anonymous instantiations in the JMapViewer constructors.
EDIT:
It does indeed appear that there is a way to access the anonymous listeners, by using the java.awt.Component method getMouseListeners(). So technically in my application I could search this collection for instances of DefaultMapController, and use that to access the methods I need to use to change the controller options.
To play devil's advocate though, if I go with original idea and give the map a reference of its controller, now I have a sort of circular reference (map knows of controller and controller knows of map). Is this a bad idea?
The abstract parent, JMapController, holds a reference to the JMapViewer passed there by the DefaultMapController constructor:
public DefaultMapController(JMapViewer map) {
super(map);
}
Addendum: The map reference held by the controller is used to (selectively) add up to three controller references to the map's EventListenerList, discussed here. Any one of these would preclude GC. At least one salutary design benefit is that a concrete JMapController need only implement available interfaces.
As suggested in this MVC outline, it would be unusual to give the view a reference to the controller. In contrast, there's nothing wrong with letting the controller register as a listener to the view, as suggested here.
Note that only the no-argument JMapViewer constructor installs a DefaultMapController. You can use the alternate constructor, as noted in comments at line 57-59 in revision 29113 of Demo.java. A complete example is examined here.
1) Everything you know is that, if and when the VM deems it to be appropriate, it will collect some or all of the dead objects. The GC is not required to do anything.
2) The best thing is to ask to the maintainer of the library. Anyway, as a general rule, I would not bother to change anything unless there's a good reason to, e.g. if it sensibly improves readability, and would rather focus myself on real problems.
3) Not sure if that's the case, but, when you serialize a JComponent, you also serialize all of its fields. And you do not want to serialize a lot of unused stuff.

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources