Is there any way to access FXML variables in classes other than Controller Class? - javafx-2

I'm curious that is there any way to call #FXML variables in not only Controller Class but also in another classes. Well actually i'm dealing with SVGPath nodes and trying to implement various kind graphs. However i dont wanna write the whole code in only Controller Class. I will appreciate if you can help and also give clear answers. So thanks anyway :)
EDIT: let me introduce a simple example about my issue.
Controller class code section;
public class RiskControllerClass implements Initializable {
#FXML private SVGPath NA_1; // Alaska
#FXML private SVGPath NA_2; // NorthWest_Ter
.
.
}
Territory class which refers to a vertex in a graph
public class Territory {
public Territory(SVGPath nodeSVG, int territoryID, int playerID){
this.playerID = playerID;
this.territoryID = territoryID;
this.nodeSVG = nodeSVG;
this.label = nodeSVG.getId();
this.adjacencyList = new LinkedList<>();
this.edgeSet = new LinkedList<>();
}
.
.
}
so i want to implement my graph another class than Controller class something like GameBoard
public class GameBoard {
// Want to call #FXML instance variables here
}

There is no other way than to access your controller and call methods from it. There is no magical way an #FXML annotation makes private variables globally available. #FXML is only used to mark certain fields for the FXMLLoader so he can access them via reflection in the instantiation process of your FXML - nothing else.
Refere to this questions on how to access the controller:
Accessing FXML controller class
JavaFX: How to get stage from controller during initialization?

Related

How to use JAXB with PropertyChangeSupport?

I am trying to use JAXB in an Eclipse project. View widgets are bound to model attributes with java.beans.PropertyChangeSupport. This works fine. I want to also bind model attributes to a persistent XML representation on disk with JAXB. I can marshal important state to XML and can unmarshal that back into a pojo/bean thing at runtime but am not sure how best to proceed.
The bean setters bound to my view widgets need to firePropertyChange() but XJC generates only simple setters, this.value = value.
XJC properties are protected, so it looks like I could override its setters to firePropertyChange(), but I don't know how my overriding subclass could have its unmarshaled superclass magically change state at runtime (like when user requests report for different year which is when I would unmarshal a different XML file).
Is there an example or pattern for doing this? Surely it is not new. Many thanks. -d
#Adam Thanks! I grokked a workable solution with this:
public class MyBean extends JaxBean {
public JaxBean getJaxBean() {
return this;
}
public void setJaxBean(JaxBean jaxBean) {
super.setThis(jaxBean.getThis());
super.setThat(jaxBean.getThat());
// etc...
}
public MyBean() {
// etc...
}
}
I think my confusion was thinking the unmarshalled bean would somehow magically replace my working instance. The solution above requires additional text but it works and the use of JaxBean's dumb setters avoids firing events unnecessarily when loading a new XML.
Your solution, annotating MyBean with JAXB and using schemagen, sounds even better. I will try that next go around. These are very nice technologies. -d
I mentioned another approach to your application in my comment.
It's what we use in our RCP application. Except that we marshall/unmarshall through network thus we use JAXWS and not just JAXB.
I'm somewhat experienced with this kind of stack, so here's a kick-starter for you:
/**
* Your UI POJO-s should extend this class.
*/
public abstract class UIModel<T extends UIModel> {
protected final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
/**
* This comes handy at times
*/
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
//....
}
/**
* And this too, trust me.
*/
public void deepCopy(final T of) {
removePropertyChangeListener(propertyChangeListener);
//It's from Spring Framework but you can write your own. Spring is a fat-ass payload for a Java-SE application.
BeanUtils.copyProperties(of, this, IGNORED_ON_CLIENT);
addPropertyChangeListener(propertyChangeListener);
}
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
}
/**
* Example of a UI POJO.
*/
public class Car extends UIModel<Car> {
private String make;
private int numberOfWheels;
//... etc.
/**
* Example of a setter
*/
public void setMake(String make) {
propertyChangeSupport.firePropertyChange("make", this.make, this.make = make);
}
public String getMake() {
return make;
}
//... etc.
}
I don't know how often your Schema-definition changes but there's a pattern supporting this;
/**
* New application (compiled with the class below) can open a file saved by the old application.
*/
public class Car2 extends Car {
private String fuelType; // Example of a new field
public void setFuelType(String fuelType) {
propertyChangeSupport.firePropertyChange("fuelType", this.fuelType, this.fuelType = fuelType);
}
//... etc.
}
This way the old application can open XML-outputs of the new. Dropping a field from such a class's source code will result in a RuntimeException as JAXB is still looking for it.
If you're clients are always up-to-date then you should not care about this at all.
When tackling with Java collections and subclassing excessively you will run into JAXB problems which you can solve by Googling #XmlRootElement and #XmlSeeAlso annotations.
Comments don't format, trying "answer". Need to do the stackoverflow tour. Continuing,
Thanks, Adam, I will bookmark these for future reference. They look similar to my example, the pattern is (unmarshal New, be quiet, copy New to Old, be noisy). I like the mind-bending recursion,
class UIModel<T extends UIModel>
class Car extends UIModel<Car>
and assume you've tested it compiles. ;)
Regards, -d.

Binding a button to a different view model

I have a button in View "A" which already has a bindingSet attached to it (it binds to ViewModel "A"). I have button though which needs to be bound to ViewModel "B".
What is the best way to do this?
Your ViewModel is your Model for your View.
If that ViewModel is made up of parts, then that can be done by aggregation - by having your ViewModel made up of lots of sub-models - e.g:
// simplified pseudo-code (add INPC to taste)
public class MyViewModel
{
public MainPartViewModel A {get;set;}
public SubPartViewModel B {get;set;}
public string Direct {get;set;}
}
With this done, then a view component can be bound to direct sub properties as well as sub properties of sub view models:
set.Bind(button).For("Title").To(vm => vm.Direct);
set.Bind(button).For("TouchUpInside").To(vm => vm.A.GoCommand);
set.Bind(button).For("Hidden").To(vm => vm.B.ShouldHideThings);
As long as each part supports INotifyPropertyChanged then data-binding should "just work" in this situation.
If that approach doesn't work for you... In mvvmcross, you could set up a nested class within the View that implemented IMvxBindingContextOwner and which provided a secondary binding context for your View... something like:
public sealed class Nested : IMvxBindingContextOwner, IDisposable {
public Nested() { _bindingContext = new MvxBindingContext(); }
public void Dispose() {
_bindingContext.Dispose();
}
private MvxBindingContext _bindingContext;
public IMvxBindingContext BindingContext { get { return _bindingContext; } }
public Thing ViewModel {
get { return (Thing)_bindingContext.DataContext; }
set { _bindingContext.DataContext = value; }
}
}
This could then be used as something like:
_myNested = new Nested();
_myNested.ViewModel = /* set the "B" ViewModel here */
var set2 = _myNested.CreateBindingSet<Nested, Thing>();
// make calls to set2.Bind() here
set2.Apply();
Notes:
I've not run this pseudo-code, but it feels like it should work...
to get this fully working, you will also want to call Dispose on the Nested when Dispose is fired on your View
given that Views and ViewModels are normally written 1:1 I think this approach is probably going to be harder to code and to understand later.

Xamarin.ios initialize UIView

I am using Xamarin.iOS. I have created UIView with a few UITextFields. I am looking for best way to initialize text value in these textfields from code.
I can pass text data in the constructor of UIViewContoller, but I don't have access to textFields inside it (they are null). I can change text value of textFields in viewDidLoad method.
I don't want to create additional fields in controller class to store data passed by constructor and use them in viewDidLoad. Do you know better solution ?
I don't want to create additional fields in controller class to store
data passed by constructor and use them in viewDidLoad.
But that's how it's meant to be done.
Alternatively, you can create less fields/properties in your viewcontroller if you use a MVVM pattern:
public class UserViewModel {
public string Name { get; set;}
public string Title { get; set;}
}
public class UserViewController : UIViewController
{
UserViewModel viewModel;
public UserViewController (UserViewModel viewModel) : base (...)
{
this.viewModel = viewModel;
}
public override void ViewDidLoad ()
{
userName.Text = viewModel.Name;
userTitle.Text = viewModel.Title;
}
}
That's the kind of pattern which gives you a lot of code reuse accross platforms (android, WP, ...) and clearly separate concerns. It's a (very) little bit of extra code, but it's worth every byte.

Calling one specific overriden method in all derived classes

Consider the following code:
// ======== Abstract class ========
public abstract class Creatures {
public abstract void loseEnergy();
public void execute()
{
loseEnergy();
}
}
// ======== Animals ========
public class Animals : Creatures
{
public override void loseEnergy(){}
}
public class Birds : Animals
{
public override void loseEnergy(){}
}
// ======== Human ========
public class Human : Creatures
{
public override void loseEnergy(){}
}
public class Male : Human
{
public override void loseEnergy(){}
}
public class Female : Human
{
public override void loseEnergy(){}
}
[ This code was based on the code by Jayson suggested here: "Base class methods calling derived class methods ?" ]
In the given code example, I would like to have the runtime executing EACH derived class object's certain method, in this case, which is 'loseEnergy()', however, I could not find the solution.
How do I approach this problem?
What can be useful to know or to try.. in order to solve this issue?
Your help is very much appreciated!
Thank you!
Kind regards,
Segara
P.S. Some search I have done so far:
"How to call overriden methods in all derived classes"
"Collection of derived classes that have generic base class"
"How to call derived function using base class object"
"Call method of the derived class through reflection possible or no"
EDIT:
I decided to stick to the idea I had before which is to have some list that would contain the objects of the classes that have 'loseEnergy()' method. Having such list I will be able to call every object's method 'loseEnergy()', which is what I wanted.
Question can be closed.
Thank you.
I didn't really understand your problem but anyway i can try to give you some means to use abstract classes :
If you use a abstract method, you SHOULD override it in a subclasses (like a method declared in an interface)
If you want that all inherited class use a same method, you can implement it in the abstract class ; all subclasses will use the method you implements if you don't override it, you've have to not declare it in the subclasses (extends < ABS_CLASS > is good enough)
If you want use a method of the abstract class which is override in the sub class you can use the keyword super .
I hope it will help you.
if you mean that you want the calls: female.loseEnergy() -> human.loseEnergy() -> creature.loseEnergy(), call the base method in the first line of the overriden one
public class Female : Human
{
public override void loseEnergy()
{
base.loseEnergy();
// do stuff
}
}
In the Greenfoot environment that you mention in the post above, the act() method is called only on actors which have been added into the "world". Internally, this adds them into a list. The simulation process iterates through the list and calls act() on each object in turn. Objects that are not "in the world" are not known to the system and so do not have their act method called. There is no magic here going on here.
If you wanted similar behaviour but without manually adding objects into a list, you could possibly have the base class constructor add new objects into a global list. I don't know C# so I don't know precisely how to do this, but I cannot imagine it would be difficult.

Accessing labels, textboxes and lauching views from TableViewDatSource

Just new to Monotouch! :D Very glad with it but still in the discovery phase... Hehehe...
I was wondering if i can see/change my labels from within my Table View, for example, in the Main.cs, please take a look:
public partial class AppDelegate : UIApplicationDelegate
{
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
//Do something in here (load my view or any other thing...)
}
public class TableViewDataSourceClientes : UITableViewSource
{
//Why can't I access my labels inside this class?
}
}
So, my question is pretty much it. Why i can access my labels and views and textboxes and etc. inside FinishedLauching and not in TableViewDataSourceClientes? ANd how can I achieve this?
My objective is to create a method inside of TableViewDataSourceClientes called RowSelected and change a label text when I select a row.
You cannot access your outlets/labels in the TableViewDataSourceClientes class because they are instance properties on your AppDelegate class. You can get at the AppDelegate from anywhere with UIApplication.SharedApplication.Delegate, you'll need to cast it to your AppDelegate type tho, and then expose the fields / properties you want as public members.

Resources