assign data from dto to group of text fields in javafx - java

I'm new to JavaFX and what I'm trying to do is I have a DTO object with 15 fields that I fetch from backend which I need to show all the fields in screen
for now what I did for each filed will create textfield in fxml file and inject it in the controller using textfield id then set the text for that from the dto for example
#FXML
TextField firstName;
........
firstName.setText(dto.getFirstName)
so is there is any other way than going through each textfield and using setText to set their value

As you state that you are new to JavaFX, I do not recommend that you try to implement the potential approaches in this answer.
Investigate the controlsfx BeanPropertyUtils, PropertySheet and PropertyEditor.
Different potential implementation strategies:
You could use a collection of TextFields, e.g. a list and assign values sequentially based on, for example, position in an sql row set.
Or perform a lookup on a map of strings to TextFields based on a column name key.
Or use reflection on Java Beans (this is how controlsfx works).
But none of them would be worth implementing unless you have a great many fields and need some generic system to handle values. Otherwise I wouldn’t recommend implementing such abstract functionality.
An example of a generic use case would be if you were introspecting on an unknown large database schema.
If you do need to do this, probably your best place to start would be the controlsfx library.
SceneBuilderKit, which was used to build SceneBuilder, has similar functionality but it is not as easily accesible as ControlsFX.
I advise you review the above comments then decide if you really want to do this.
If you do, then choose one potential strategy and implement it (this won’t be done in a StackOverflow answer).
If stuck, provide a complete minimal reproducible example for a concrete example and implementation attempt in code, only for the art of the problem you are stuck on. This allows you to create a more concrete question that is greatly reduced in scope.

Related

Language switching - l10n I18n

How does language switching work in Java/Vaadin? I have a web application and would like to integrate a combo box, that changes the language of every text in this application. Do i need to mark each text that should get translated manually and define its translation? How complex is it to implement this function into an exting project?
Do i need to mark each text that should get translated manually and define its translation?
You should use ResourceBundles to store/read translations of strings.
How does language switching work in Java/Vaadin?
You need to provide a class that implements I18NProvider. Documentation about that can be found here
Once implemented correctly, you will be able to call getTranslation("HelloWorld") on any Component (and therefore on any view since they must extend a component), to receive the translation of the key "HelloWorld" defined in the ResourceBundle-file of the current UI-Locale.
Views that extend LocaleChangeObserver are notified when the Locale is changed, and then you can call getTranslation("HelloWorld") again to find the translation of the freshly set language.
I would like to integrate a combo box, that changes the language of every text in this application.
See this SO answer of mine where I posted example code of a Select component that acts as a language switcher. It is using both ResourceBundle and I18NProvider. (You can use a ComboBox too, but with the downside that you can only display a String for the selected value)
The important part in that code there is that the Select has a ValueChangeListener that sets the Locale of the VaadinSession, which in turn will trigger the localeChange method of the LocaleChangeObserver that your view now should implement. In the localeChange method, you can re-translate the translatable Strings of every component in the view; set new texts in Labels, set new labels and placeholders for TextFields, etc etc.
How complex is it to implement this function into an exting project?
That depends very much on your definition of complex, and how familiar you already are with ResourceBundles. There certainly are less complex topics than this, but I18N is never easy. In my opinion, Vaadin has done a very great job of providing us devs with a way to use I18N in our applications.
Most people use a sort of translation file system for their localization. Basically you make a text file for each language with a key and value system where you name every translated message with a key and a translated value. You can then use these keys (that should be predefined) to get the correct message for the language you want. These files can be anything really, but if you're looking for a simple java implementation then there are pretty simple ways to do it. For an example look here.
Did you look at this section of the documentation? https://vaadin.com/docs/v14/flow/advanced/tutorial-i18n-localization.html

Xpages "Views" with beans: Categorize, Sort, Search

I'm trying to do the OOP approach in all my xPages. As expected I'm facing several issues, but also have tons of advantages doing so.
My question is related to Views (Repeat controls). I am loading a List<myCustomBean> for my repeat controls that contains all available objects of type myCustomBean and display each myCustomBean the way I want in a Bootstrap table row. That works all fine.
I'm able to sort my List with URL parameter sortedBy=MySortColumn with my own method. - Problem 1 solved.
How would I approach a Categorization in my Repeat Control? So I could easily sort the beans by the Cotegory, but how would I display it, incl. expandable and collapsible twisties? Maybe there is a Custom control that I can use? Or a Control of the Extension Library?
Or do I have to build everything from scratch myself?
Any advice is much appreciated.
The Data View control is probably the best. Like the View Panel or Data View, it's a extension of the Repeat Control. But it has much more flexibility that the View Panel and allows much more configurable layout than the Data View. It has a categoryColumn property, but that's designed for binding to a dominoView datasource. But there is also the categoryRow facet which can be used.
Essentially, using a dominoView component is already using OOP programming. Your repeat is using List<myCustomBean>, dominoView returns List<DominoViewEntry>. Properties on the dominoView are used to interrogate the underlying View object within the database and return only those ViewEntry objects from the ViewNavigator or ViewEntryCollection that are required. It wraps the ViewEntry as a DominoViewEntry object for just a selection of those, based on the rows property of whatever uses the DominoView.
As someone who built a subset of that functionality for use from Vaadin (see my XPages to Web App blog series http://www.intec.co.uk/tag/xpages-to-web-app-tutorial/), within XPages I typipcally use the dominoView object unless I'm extracting a small subset of ViewEntries / Documents. When I use ViewEntryCollection / DocumentCollection, I rarely wrap, preferring to let XPages optimise retrieval rather than re-develop that optimisation myself.

Polymorphism and boxes

I am trying to get round a rather annoying issue in my homework.
Basically the task is to create a fake ordering UI where the user puts in some variables about the type of box they need to order and then presses a button. Behind the scenes the app should be validating which pipe fits the users needs and then instantiate a new box object and execute the methods inside the new object.
I am basically struggling to find a way that isn't stupid which allows for the UI to validate a choice before creating a new object, a method is given to us to begin with and is referred to a 'brute force method' which has a massive if statement inside the button click which does the checking there, now I am 100% sure there is an easier way to do it although the only thing I can come up with is holding constants or statics in a class and checking each class before creating one.
Scenario:
The idea is that each box the company sells has certain features (thickness, laminated, colour and other things) while others boxes don't, I need to be able to figure out when the order button is clicked what box the order fits once I know the box type that the order fits I should create a new object of that box and run the cost() method, if it doesn't fit any box the company sells then I should prompt the user. The program must use abstraction.
The class isn't at a high level at the moment so I can't use enums and lookup tables which is causing me problems.
Thanks for any help in advance.
Sounds to me like they just want you to show several classes (one for each type of box) which all inherit or implement a common interface with methods like 'getWidth', 'getHeight' etc. You can then write a simple loop to iterate over a collection of box type instances, evaluating their suitability before returning the list of compatible box types.

Displaying class contents in a GUI with Swing

I have some classes with fields and getters/setters and I want to display the fields of the class in a Swing application.
The name of each field should be dosplayed in a Label and the value should be displayed depending on the type of the value, i. e. String uses a TextField, List uses a ComboBox and so on.
One difficulty is that the class can contain fields, which also need to be treated this way itself.
Is there a recommended/standard way of doing that?
I looked a bit into java.beans but I'm not really sure if it isn't primarily used when the class is a Swing component itself.
Another option is to use PropertySheet component from L2FProd. From you description it should do exactly what you wanted.
It wasn't updated for a long time but works well.
I don't think there is an automated way to accomplish this. In fact I think you might even be approaching it incorrectly. What if you List contains objects other than Strings for example, how is a JComboBox going to break this out? I would suggest just using a JTable and putting the name in the first column and the value in a second column.
You could add #Annotations to your fields you want to examine and display in the GUI. In every case you have to use reflections to access and find all the fields you want to display. I think you have to add a custom logic to the databinding which examines a given class for it's fields (maybe filtered with a #Display annotation or stuff like this).
This should be very easy to implement, you can rely on the POJO Bean definition and access all the fields over getter/setter, don't forget to cache the handled classes to avoid circular dependencies of classes.
I hope this helps.
There is ReflectionUI. It can display primitive values objects and lists by just using reflection. It works well with getter/setter properties.

java / gwt UI coding - clean code

i've started on some basic java coding with gwt, and im getting a bit concerned about the heft of my main class.
For instance - how does one compartmentalize the keyhandlers, since they trigger a number of changes to the UI, how could i move this into a separate .class file and still be able to access all the various widgets in the main class, without having to pass everything to the handler (ie. all the widgets i manipulate after the click event).
i've googled but didnt come across any particularly good examples - know of any readily legible code-bases i could read to see how it should be done? (gwt's own tuts are pretty basic, and just kitchen-sink every thing into a single file)
thanks!
I hate to say something so unimaginative, but MVC works--it's not the ultimate, but it can start getting you organized.
EDIT: While searching on a semi-related topic, I came across this which has similar ideas to mine but goes into more detail.
What that means in terms of GWT is that you should think of just laying out your GUI components in one class, put all your event handling in a second and put your object model objects separate from the other two.
One way to accomplish this is to make most or all the controls on your GUI public members. This sounds kind of lame, but their usage is encapsulated inside the controller so it's not like you have uncontrollable access--in fact your access is clearer/better defined than if all your members were private but your view code was combined with the controller.
Specific tricks:
Have listeners be their own class. You can often reuse them-- in other words, avoid anonymous inner classes. I sometimes create a listener class and instantiate a new instance for each button/control that needs to have a similar effect when pressed. If I need it to act slightly differently for a given button, I'll pass something into the constructor of the "special" handlers so that they know to act a little differently. You can also create different handler sub-classes if necessary--I'm just saying don't forget that event handlers are classes, you can use inheritance and everything if need be.
One Very Old GUI Trick I learned a long time ago, try not to have various mini-handlers modifying the GUI in different ways, instead have all the "active" buttons and controls set a state within your GUI and then call a single method that applies that state to ALL the controls on your GUI. When you get beyond a trivial GUI this can be a life-saver. If I'm not being clear, leave a comment and I'll leave an example for you.
Property sheets:
There is a special case for GUIs--the property sheet style GUI. I've done a LOT of these and they are irritating as HELL. They tend to have dozens or hundreds of controls on them, each GUI control tends to be tied to a specific field in your model and there are just hundreds of lines of copy and paste boilerplate code connecting them, each group copied and pasted with a few items changed--at minimum it's like 3 lines of code per control (Create control, copy value in and copy value out).
I always write these with a "Smart" controller--one that can intelligently bind the control to some data without any unique code. This can get tricky and if this is your problem let me know in the comments and I can give you some general advice as to some tricks you might try. I've gone from a minimal reflective solution to a full-on XML based solution. Were I to do it again, I might consider annotation-based.
Example of MVC:
Note, this is just an example, there are a MILLION ways to do MVC.
In your MAIN:
Instantiate MyView
Instantiate MyModel
Instantiate MyController(myView, myModel)
myView.setVisible(true)
in MyView
probably extends Frame
Most components are public final (public final Button b=new Button())
If public members make you nervous, use getters--same EXACT effect as public final members with a little extra syntax.
Remember that you can set final members in your constructor.
May have general methods such as reset(), but MyController may be a better place for this.
in MyController
saves references to myView and myModel
adds listeners to myView where necessary (see advice on listeners above)
configures myView based on state of myModel
when "done" button pressed, copies state from myView to myModel
notifies myModel that it's data has been updated and destroys itself.
in MyModel:
This would be a typical model class, it would contain your business logic (mostly not used as part of the GUI, that's more like GUI logic in MyController. The controller would tend to set values in your business logic then call some method like updated() to cause some business logic to take control. It should know nothing of a GUI--this is your "pure" business class.
Sometimes the GUI might call an update() or some other method to trigger some data change and then reload the GUI controls from the Model--this is a fairly good way to integrate your business logic with your GUI without your model knowing about the GUI...
Also, as I said above, I would put more work into MyController if I was working with property sheets just due to the sheer number of lines of boilerplate that you end up with if you aren't smart about it.
Note that View and Controller are nearly always paired. You can't just replace a Swing view with a web view and expect the controller to remain unmolested--but the model should not ever change for the view or controller.
You should take a look at the best practices for GWT applications first:
http://code.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
One of the concepts they talk about is that of MVP (not MVC) to structure your application. There's a sample project on Google Code that you can look at to understand how to structure a GWT application in this way:
http://code.google.com/p/gwt-mvp/

Categories

Resources