Serialize JavaFX components - java

I'm trying to develop a little drag & drop application under Java FX. User will drop JFX components like Buttons, Menus, Labels on certain positions. When done, he will save this layout and later on he will reopen the layout and he will use it again.
Its important to store the information about all objects that are dropped on some position.
I decided to use serialization for this purpose. But I'm not able to serialize JavaFX components. I tried to serialize Buttons, Scenes, Stages, JFXPane but nothing seemed to work (I obtained NotSerializableException).
Any suggestions how to save all the components and then retrieve them ?
P.S.: I was trying to find out some method with FXML but I did not succeed.
Thank you very much for your answers :)

You are correct, JavaFX (as of 2.1) does not support serialization of components using the Java Serializable interface - so you cannot use that mechanism.
JavaFX can deserialize from an FXML document using the FXMLLoader.load() method.
The trick though, is how to write your existing components and states out to FXML?
Currently, there is nothing public from the platform which performs FXML serialization. Apparently, creating a generic scenegraph => FXML serializer is quite a complex task (and there is no public 3rd party API for this that I know of). It wouldn't be too difficult to iterate over the scenegraph and write out FXML for a limited set of components and attributes.

If the main goal of saving user components on the servers side - is to have a possibility to show the same interface to the user - why not to save all descriptive information you need about users components, and when it is needed - just rebuild user interface again, using stored descriptive information? Here is primitive example:
/* That is the class for storing information, which you need from your components*/
public class DropedComponentsCoordinates implements Serializable{
private String componentID;
private String x_coord;
private String y_coord;
//and so on, whatever you need to get from yor serializable objects;
//getters and setters are assumed but not typed here.
}
/* I assume a variant with using FXML. If you don't - the main idea does not change*/
public class YourController implements Initializable {
List<DropedComponentsCoordinates> dropedComponentsCoordinates;
#Override
public void initialize(URL url, ResourceBundle rb) {
dropedComponentsCoordinates = new ArrayList();
}
//This function will be fired, every time
//a user has dropped a component on the place he/she wants
public void OnDropFired(ActionEvent event) {
try {
//getting the info we need from components
String componentID = getComponentID(event);
String component_xCoord = getComponent_xCoord(event);
String component_yCoord = getComponent_yCoord(event);
//putting this info to the list
DropedComponentsCoordinates dcc = new DropedComponentsCoordinates();
dcc.setX_Coord(component_xCoord);
dcc.setY_Coord(component_yCoord);
dcc.setComponentID(componentID);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getComponentID(ActionEvent event){
String componentID;
/*getting cpmponentID*/
return componentID;
}
private String getComponent_xCoord(ActionEvent event){
String component_xCoord;
/*getting component_xCoord*/
return component_xCoord;
}
private String getComponent_yCoord(ActionEvent event){
String component_yCoord;
/*getting component_yCoord*/
return component_yCoord;
}
}

Related

Vaadin change value from nested Layout

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.

How to pass arguments in JavaFX

So, it's a little confusing but here is the thing:
I created a window with SceneBuilder, and created the controller and everything, there is a button in the window.
The button setOnAction() method makes the program open another window, the thing is, this other window is another class and I want to pass information to this other window, but it seems I cannot. Here's some code example:
MainWindow:
confirm.setOnAction(event->{
try {
LibraryWindowController lwc = new LibraryWindowController();
lwc.setDay(day.getValue());
lwc.setMonth(month.getValue());
lwc.setYear(Integer.parseInt(year.getText()));
lwc.setClient(login.getText());
lwc.start(new Stage());
} catch (Exception e) {
System.out.println("An error has occured!");
}
});
LibraryWindowController (variables and setters):
private int day, month, year;
private String client;
public void setDay(int day){
this.day = day;
}
public void setMonth(int month){
this.month = month;
}
public void setYear(int year){
this.year = year;
}
public void setClient(String login){
this.client = login;
}
The thing is, inside the Controller's initialize method there is a System.out.println(client);
and the problem is that the output is null, so, why is that happening and how to fix it?
I recommend you use the fx:root construct to prevent issues like this. I find it helps greatly with structuring your app. It is described in the Custom Components section of the FXML docs. If you use this approach, all your screens/panes are simple subclasses of some Pane class in JavaFX. And because the FXML loading is encapsulated in the class, you can simply use the constructor to create new instances (see the example in the documentation I linked to) and set them up as you would any object.
For example (assume MyPane is a Pane you designed using this approach):
MyPane mp = new MyPane();
mp.setWhatever(whatever);
Stage newWindow = new Stage();
newWindow.setScene(new Scene(mp));
newWindow.show();
All you have to change in SceneBuilder is remove your controller class (you no longer need it, class MyPane itself becomes the controller) and check the "Use fx:root" checkbox.
For a complete example of how to use fx:root, see this example I made for my students. It comes with the complete source code (on GitHub).
With regard to your code: you call LibraryWindowController a controller, but from the looks of it I assume it's an Application? You don't need to create separate applications to create multiple windows. Simply create a new stage with a scene and a root node. However, the steps you used should have worked, even if they aren't recommended. I'm guessing either login.getText() returns null or you have an error elsewhere in your code.

I'm new to java from a javascript background: how do they manage event listeners properly and not tighting classes together?

I've been trying to do some "simple thing" in java that in javascript would look like:
// Main class
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
Well in java what I found so far is making the Main class deriving from java.util.Observer and Model from java.util.Observable; Then when the model will dispatch the event it will call the update method on the Main class. I found really ugly and not elegant at all. I can't even think of how I could work with this;
Is there any cleaner and flexible ways, maybe some libs to help me out here, because I have not found any acceptable tutorial about how to do it like this?
thanks a lot
Well what I've managed so far, and I quite I like it a lot more than creating "empty" classes just for simple events (but still not good, at least for me):
private ArrayList __items;
public void addListener(Method method, Object object){
this.__listeners.add(new Object[] {method, object});
}
public void dispatch(){
int i = this.__listeners.size();
Method method;
Object context;
while(i>0){
i--;
method = (Method)(this.__listeners.get(i))[0];
context = (Object)(this.__listeners.get(i))[1];
try{
method.invoke(context);
}catch(java.lang.reflect.InvocationTargetException e){
}catch(java.lang.IllegalAccessException e){
}
}
}
Then I use like this:
Gifts gifts = prendastotty.PrendasTotty.getMain().getLoggedUserGifts();
Class[] parameterTypes = new Class[0];
try{
Method m = Home.class.getMethod("__updateTable", parameterTypes);
gifts.addListener(m, this);
}catch(NoSuchMethodException e){
}
It this leaky/anti-pattern/buggy?
I must say that I had a bit of trouble keeping up with your code because in my head some of the stuff didn't make sense (from a Java way of thinking, or at least my Java way of thinking). So I hope I understood you correctly and can help you out.
Let's first take your simple example:
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
In Java a good approach,for example, would be:
public interface ModelListener {
public void execute(Model context);
}
public class Model {
private List<ModelListener> listeners;
public Model() {
this.listeners = new ArrayList<ModelListener>();
}
public void addListener(ModelListener listener) {
this.listeners.add(listener);
}
public void dispatch() {
for (ModelListener listener: listeners) {
listener.execute(this);
}
}
}
With this sort of design you can now do one of two things:
Use anonymous classes
In Java the most common case is that all your classes have a name, although there are cases when you can create anonymous classes, these are basically classes that
are implemented inline. Since they are implemented inline, they're usually only
used when they're small and it's known they won't be re-usable.
Example:
Model model = new Model();
model.add(new ModelListener() {
public void execute(Model model) { /* do something here */ }
});
Notice how the new ModelListener object is created (which is an interface) and the execute implementation is provided inline. That is the anonymous class.
Interface Implementations
You can create classes that implement your interface and use them instead of anonymous classes. This approach is often use when you want your listeners to be re-usable, have names that give semantic meaning to the code and/or they're logic isn't just a few lines of code.
Example:
public class LogListener implements ModelListener {
public void execute(Model model) {
// Do my logging here
}
}
Model model = new Model();
model.addListener(new LogListener());
Side note
As a side note, I saw that the method you were trying to bind as a listener was called __updateTable are you by any chance trying to detect object's changes so you can commit them to the database? If so I strongly suggest you to look at some ORM frameworks such as Hibernate or JPA they'll keep all that hassle from you, keeping track of changes and committing them to the database.
Hope it helps, regards from a fellow portuguese StackOverflow user ;)
You will find it a bit difficult to try to directly map javascript ideology into java. Their underlying philosophies are different. Without more definite code and expectations it is difficult to give you a clearer answer. Here is a sample of code in GWT(written in java) that attaches a click handler to a button.
Hope this helps you get started.
myButton.addSelectionListener(new SelectionListener<ComponentEvent>(){
#Override
public void componentSelected(ComponentEvent ce) {
// do your processing here
}
});
In Java, a function can't exist outside of a class as it can in Javascript. So when you need to provide a function implementation at runtime, you have to wrap that function inside a class and pass an instance of the class, unfortunately.
The solution you have using reflection will work (I assume), but it is not the preferred way to do it in Java since what used to be compile-time errors will now be runtime errors.

Sending messages to a swing JTextArea from different places

I have a JTextArea always visible in my main app window (a Log if you like), and I want to use it to display activity going on in the system (like mock-debug output you'd do with System.out.println() in if conditions or whatever)
I mean high level things the user does, (like "successfully loaded file " or " written to disk", " completed" etc)
Thing is such messages can be generated anywhere in my system mainly in another package the classes of which deal with the data and computation, and they're unaware of the GUI.
Maybe save the messages to a temp file and the textarea "monitors" that file for changes, how can this be done?
The simplest way is to define a logger interface:
package com.example.logging;
public interface ActivityLogger {
void logAction(String message);
}
Then pass it to your non-GUI components so they don't get tied to a specific implementation:
public class FileLoader {
private ActivityLogger logger;
public FileLoader(ActivityLogger logger){
this.logger = logger;
}
public void loadFile(){
// load stuff from file
logger.logAction("File loaded successfully");
}
}
Now, making an implementation that writes to a text component is simple:
public class TextComponentLogger implements ActivityLogger{
private final JTextComponent target;
public TextComponentLogger(JTextComponent target) {
this.target = target;
}
public void logAction(final String message){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
target.setText(String.format("%s%s%n",
target.getText(),
message));
}
});
}
}
// Usage:
JTextArea logView = new JTextArea();
TextComponentLogger logger = new TextComponentLogger(logView);
FileLoader fileLoader = new FileLoader(logger);
fileLoader.loadFile();
You can of course also use a standard logging framework (java.util.logging, slf4j, log4j, etc) and write an appender that "writes" to a text component.
The design can be rather complicated. Maybe you can have a public access method like updateText() in the class where your TextArea would be. Then you create a kind of 'resource' or 'shared' class (just a plain class) that would be initialized together when your main() runs. When the class containing your TextArea is created, an instance would be placed into the 'shared' class (this shared class should be a singleton) and so all the other classes call this 'shared' class (maybe a method like updateTextArea()) and what it would do is call the class containing the TextArea via that instance and call the TextArea to update text.
The Message Console might be what you are looking for.
Java also has a "Logger" API.
You can use EventBus to decouple your GUI from the other parts of your application. (My blog has another introduction). You could do something as follows:
public class LogArea extends JTextArea {
public static final String LOG_TOPIC = "logarea_topic";
public LogArea() {
super();
// Read in the annotations, register self as a listener to the topic
AnnotationProcessor.process(this);
}
#EventTopicSubscriber(topic=LOG_TOPIC)
public void logEvent(String topic, String text) {
append(text + "\n");
}
}
public class DomainClass {
public void foo() {
// Send out a notification throughout the system to whichever components
// are registered to handle this topic.
EventBus.publish(LogArea.LOG_TOPIC, "some text you want to appear in the log area");
}
}
In a real system you'd probably want to move the topic declarations to another class so that one can use it without being tied to a specific implementation. E.g. you could have a Topics class that just contains the static string constants of the topics. Then you can have multiple classes that listen to those topics and process the messages (e.g. you could have a standard logging framework which writes out to a log file in addition to the jtextarea component).

progress bars + MVC in Java =?

So I have this nice spiffy MVC-architected application in Java Swing, and now I want to add a progress bar, and I'm confused about Good Design Methods to incorporate a JProgressBar into my view. Should I:
add a DefaultBoundedRangeModel to my controller's state, and export it?
class Model {
final private DefaultBoundedRangeModel progress
= new DefaultBoundedRangeModel();
public void getProgressModel() { return progress; }
public void setProgressCount(int i) { progress.setValue(i); }
}
class Controller {
Model model;
int progressCount;
void doSomething()
{
model.setProgressCount(++progressCount);
}
}
class View {
void setup(Model m)
{
JProgressBar progressBar = /* get or create progress bar */ ;
progressBar.setModel(m.getProgressModel());
}
}
/* dilemma: Model allows progress to be exported so technically
all of the progress state could be set by someone else; should it be put
into a read-only wrapper? */
use JGoodies Binding to try to connect the JProgressBar's visual state to my model's state?
class Model {
private int progress;
public void getProgressCount() { return progress; }
public void setProgressCount(int i) { progress = i; }
}
class View {
void setup(Model m)
{
ProgressBar progressBar = /* get or create progress bar */ ;
CallSomeMagicMethodToConnect(m, "progressCount", progressBar, "value");
// is there something that works like the above?
// how do I get it to automatically update???
}
}
or something else???
edit: more specifically: could someone point me to a Good Example of realistic source for an application in Java that has a status bar that includes a progress bar, and has a decent MVC implementation of it?
No (to 1) and NOOOO (to 2). At least in my opinion.
No (to 1): First, DefaultBoundedRangeModel is a javax.swing class. In my opinion, these classes have no place in models. For example, think about the model living on the server, being accessed via RMI - All of the sudden putting a javax.swing class there seems "not right".
However, the real problem is that you're giving a part of your model (the bounded model) to someone else, with no control over events fired or queries made.
No (to 2): Ugh. Binding is fun but (at least in my opinion) should be used to synchronize between UI model and UI components, not between data model and UI model. Again, think what would happen if your data model lived on a remote server, accessed by RMI.
So what? Well, this is only a suggestion, but I'd add an event listener interface and add the standard event listener subscription methods (addListner(...), removeListener(...)). I'd call these listeners from within my model when I have updates going on. Of course, I'd make sure to document the calling thread (or say it cannot be determined) in order for the client (the UI in this case) to be able to synchronize correctly (invokeLater and friends). Since the listener service will be exposed by the controller, this will allow the model to live anywhere (even allowing for listeners to be remotely invoked or pooled). Also, this would decouple the model from the UI, making it possible to build more models containing it (translators / decorators / depending models).
Hope this helps.
I would say, something else.
The problem I have had with MVC, is to define the level of abstraction of the model.
Model could be some sort of objects for the UI components
Model could also be some other sort of objects for the program it self.
and
Model could be as high as business models.
In this case I would have separated model/component pairs for the progress bar and handle them in a separate controller class.
This article describes swing architecture and might clarify the way it uses models inside.
In our app (MVC, about 100 KLOC) we have it like that (pattern Observer, actually):
/**
* Observer on progress changes
*/
public interface IProgressListener {
public void setProgress(ProgressEvent e);
}
public class ProgressEvent extends ... {
private int progressCount;
// setter + getter
...
}
class Model {
public void addProgressListener(IProgressListener l);
protected void fireProgressChange(ProgressEvent e); // call .setProgress() on listeners
}
class Controller {
private Model model;
}
class View extends ProgressBar implements IProgressListener {
...
// IProgressListener implementation
public void setProgress(ProgressEvent e) {
this.setValue(e.getProgress());
}
...
}

Categories