Created
January 22, 2016 07:47
-
-
Save anton-johansson/dcc3108acf223689975e to your computer and use it in GitHub Desktop.
Load FXML views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.antonjohansson.svncommit2.core.ioc; | |
import com.antonjohansson.svncommit2.core.ui.IView; | |
import java.io.IOException; | |
import java.net.URL; | |
import com.google.inject.AbstractModule; | |
import com.google.inject.Provider; | |
import javafx.fxml.FXMLLoader; | |
import javafx.scene.Parent; | |
/** | |
* Extension of {@link AbstractModule} that provides extra utility methods | |
* for binding in the {@code svn-commit} application. | |
* | |
* @author Anton Johansson | |
*/ | |
public abstract class AbstractApplicationModule extends AbstractModule | |
{ | |
/** | |
* Binds a view instance. | |
* | |
* @param viewClass The class of the view. | |
*/ | |
protected <V extends IView> void view(Class<V> viewClass) | |
{ | |
bind(viewClass).toProvider(new ViewProvider<V>(viewClass)); | |
} | |
/** | |
* Provides {@link IView} implementations through FXML. | |
* | |
* @param <V> The view to provide. | |
* @author Anton Johansson | |
*/ | |
private class ViewProvider<V extends IView> implements Provider<V> | |
{ | |
private final Class<V> viewClass; | |
private ViewProvider(Class<V> viewClass) | |
{ | |
this.viewClass = viewClass; | |
} | |
@Override | |
public V get() | |
{ | |
String name = viewClass.getSimpleName() + ".fxml"; | |
URL location = viewClass.getResource(name); | |
try | |
{ | |
FXMLLoader loader = new FXMLLoader(location); | |
Parent parent = loader.load(); | |
V view = loader.getController(); | |
view.setParent(parent); | |
return view; | |
} | |
catch (IOException e) | |
{ | |
throw new RuntimeException(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment