vaadin6+spring: add custom component to application - spring

when I use this code the result is empty page:
public class Vaadin6biuApplication extends Application {
#Override
public void init() {
xx a = new xx();
Window w = new Window("aness conf");
w.addComponent(a);
setMainWindow(w);
}
}
public class xx extends CustomComponent {
#AutoGenerated
private AbsoluteLayout mainLayout;
#AutoGenerated
private Button button_1;
public xx() {
buildMainLayout();
setCompositionRoot(mainLayout);
}
#AutoGenerated
private AbsoluteLayout buildMainLayout() {
mainLayout = new AbsoluteLayout();
mainLayout.setImmediate(false);
button_1 = new Button();
mainLayout.addComponent(button_1, "top:100.0px;left:100.0px;");
return mainLayout;
}
}
how to add custom component to application?
thank you for your answers

Have you read the wiki tutorial for vaadin6 + spring? With spring > 2.5 it's fairly simple:
#Configurable(preConstruction = true)
public class SpringHelloWorld extends com.vaadin.Application {
#Autowired
private MyBeanInterface bean;
public void init() {
final Window main = new Window("Hello window");
setMainWindow(main);
main.addComponent(new Label( bean.myMethod() ));
}
}

Related

Spring data jpa with java FX

I'm using Spring JPA with OpenJFX. It's this project JavaFX-weaver, simply adding spring-boot-start-data-jpa inside pom.
However my starting time of Spring JPA is 15-20s and the UI will not show until spring is initalized. When users will start the application it takes a lot of time, every time!
As a workaround i tried to create a simply java fx application without Spring (using this demo here) and then starting there in the main method the main method from spring over a button (see example bellow). That will start spring, but dependencies and properties are not laoded.
Do you know a good way to practice that case ? Every help is welcome.
Thank you
AppBootstrap (Java + OpenJFX)
public class AppBootstrap extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
// start spring jpa main method
btn.setOnAction(event -> App.main(new String[]{""}));
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
public static void main(String[] args) {
launch();
}
}
App (Spring JPA + javafx-weaver)
#SpringBootApplication
public class App {
public static void main(String[] args) {
Application.launch(SpringbootJavaFxApplication.class, args);
}
}
Startup of an JPA powered Application increases load time for ApplicationContext. While you can make things faster by not checking or creating a database scheme, e.g. by setting hibernate.hbm2ddl.auto=none, this is not the best option.
It is by design that the primary stage is shown after the ApplicationContext is loaded, since it should be able to be dependency injected.
The best practice I recommend is using a splash screen while loading the ApplicationContext. It's a bit tricky, since you have separate Threads, but roughly it looks like this:
Create a splash window
public class Splash {
private static final int SPLASH_WIDTH = 200;
private static final int SPLASH_HEIGHT = 200;
private final Parent parent;
private final Stage stage;
public Splash() {
this.stage = new Stage();
stage.setWidth(SPLASH_WIDTH);
stage.setHeight(SPLASH_HEIGHT);
Label progressText = new Label("Application loading ...");
VBox splashLayout = new VBox();
splashLayout.setAlignment(Pos.CENTER);
splashLayout.getChildren().addAll(progressText);
progressText.setAlignment(Pos.CENTER);
splashLayout.setStyle(
"-fx-padding: 5; " +
"-fx-background-color: white; " +
"-fx-border-width:5; " +
"-fx-border-color: white;"
);
splashLayout.setEffect(new DropShadow());
this.parent = splashLayout;
}
public void show() {
Scene splashScene = new Scene(parent);
stage.initStyle(StageStyle.UNDECORATED);
final Rectangle2D bounds = Screen.getPrimary().getBounds();
stage.setScene(splashScene);
stage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2.0);
stage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2.0);
stage.show();
}
public void hide() {
stage.toFront();
FadeTransition fadeSplash = new FadeTransition(Duration.seconds(0.3), parent);
fadeSplash.setFromValue(1.0);
fadeSplash.setToValue(0.0);
fadeSplash.setOnFinished(actionEvent -> stage.hide());
fadeSplash.play();
}
}
Initialize Application
public class SpringbootJavaFxApplication extends Application {
private ConfigurableApplicationContext context;
class ApplicationContextLoader extends Task<Void> {
private final Stage primaryStage;
ApplicationContextLoader(Stage primaryStage) {
this.primaryStage = primaryStage;
}
#Override
protected Void call() {
ApplicationContextInitializer<GenericApplicationContext> initializer =
context -> {
context.registerBean(Application.class, () -> SpringbootJavaFxApplication.this);
context.registerBean(Stage.class, () -> primaryStage);
context.registerBean(Parameters.class,
SpringbootJavaFxApplication.this::getParameters); // for demonstration, not really needed
};
SpringbootJavaFxApplication.this.context = new SpringApplicationBuilder()
.sources(JavaFxSpringbootDemo.class)
.initializers(initializer)
.run(getParameters().getRaw().toArray(new String[0]));
return null;
}
}
#Override
public void start(Stage primaryStage) {
var splash = new Splash();
splash.show();
final ApplicationContextLoader applicationContextLoader = new ApplicationContextLoader(primaryStage);
applicationContextLoader.stateProperty().addListener((observableValue, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
context.publishEvent(new StageReadyEvent(primaryStage));
splash.hide();
}
});
new Thread(applicationContextLoader).start();
}
#Override
public void stop() {
this.context.close();
Platform.exit();
}
}

Binding to a Xamarin Listview via web service

I am trying to launch a interface method and bind it to a Xamarin list view but I am having some trouble. My interface is below
readonly string url = "http://myinternaliis/api/";
readonly IHttpService httpService;
public ApiClient(IHttpService httpService)
{
this.httpService = httpService;
}
public Task<List<JobsList>> GetJobs() => httpService.Get<List<JobsList>>($"{url}job");
I am trying to bind it to my list view as such please correct me if this is wrong. Should I be creating a collection of some description
public partial class JobsPage : ContentPage
{
readonly string url = "http://myinternaliis/api/";
public IHttpService httpService;
public IApi FuleApiClient;
public JobsPage ()
{
InitializeComponent ();
FuelApiClient _client = new FuelApiClient(httpService);
this.JobListing.ItemsSource = _client.GetJobs();
}
You need to await your task.
public partial class JobsPage : ContentPage
{
readonly string url = "http://myinternaliis/api/";
public IHttpService httpService;
public IApi FuleApiClient;
public JobsPage ()
{
InitializeComponent ();
FuelApiClient _client = new FuelApiClient(httpService);
SetItemSource();
}
private Task SetItemSource()
. {
. JobListing.ItemsSource = await _client.GetJobs();
}
}

Adding Custom Dialog to Javafx with Spring DI

I have a gui built with javafx the controllers are loaded from fxml and created as Beans with spring so I can access my model. But that is predefined in fxml and loaded at start. Now I would like to load components, defined in fxml at runtime, but I could not yet find a working example, and no matter how I try it doesn't work.
So my question:
How can I create a custom Dialog (or any custom component) in runtime , that is loaded from .fxml and is aware of (Spring application) context?
Edit
So it loads but some fields are not initialized.
This is my custom DialogPane,
#Controller
#Scope("prototype")
public class NewProgramDialogPane extends DialogPane implements Initializable {
public static final ButtonType buttonTypeOk = new ButtonType("Create", ButtonBar.ButtonData.OK_DONE);
public static final ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
public TextField nameField;
public TextField data1Field;
public TextField data2Field;
public RegexValidator requiredField1;
public RequiredField requiredField2;
public RequiredField requiredField3;
public ErrorLabel duplicateProjectErrorLabel;
private SimpleBooleanProperty match = new SimpleBooleanProperty(false);
#Autowired
MainService mainService;
public NewProgramDialogPane() {
URL url = getClass().getClassLoader().getResource("com/akos/fxml/NewProgramDialog.fxml");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(url);
loader.setRoot(this);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
this.lookupButton(buttonTypeOk).addEventHandler(ActionEvent.ACTION, event -> {
if (!validate()) {
event.consume();
}
});
duplicateProjectErrorLabel.visibleProperty().bind(match);
}
public boolean validate() {
requiredField1.eval();
requiredField2.eval();
requiredField3.eval();
match.set(mainService.getPrograms().stream().anyMatch(
program -> program != null && program.getName().equals(nameField.getText())));
return !match.get() &&
!requiredField1.getHasErrors() &&
!requiredField2.getHasErrors() &&
!requiredField3.getHasErrors();
}
}
And when I try to read the nameField, it is null.
public class NewProgramDialog extends Dialog<Program> {
public NewProgramDialog() {
this.setDialogPane(new NewProgramDialogPane());
this.setTitle("New program");
this.initModality(Modality.APPLICATION_MODAL);
this.initStyle(StageStyle.DECORATED);
this.setResultConverter(param -> {
if (param == NewProgramDialogPane.buttonTypeOk) {
int x = 0;
return new Program(((NewProgramDialogPane) getDialogPane()).nameField.getText());
}
return null;
});
}
}
Define your custom dialog using the custom component FXML pattern; then just expose the custom component as a (prototype-scoped) spring bean.

How to display an image on a UiApplication in BlackBerry?

How to display an image on a UiApplication?
I have a code that displays a button and when clicked it goes to a MainScreen, but I'd like to display an image below that button. I found a way to insert a zoomable image but not a static one.
Here's my code so far:
public class HelloWorldDemo extends UiApplication {
private MainScreen _screen;
private ButtonField _nextScreen;
public static void main(String[] args) {
HelloWorldDemo instance = new HelloWorldDemo();
instance.enterEventDispatcher();
}
public HelloWorldDemo() {
EncodedImage myImg = EncodedImage.getEncodedImageResource("k.jpg");
ZoomScreen zoomableImg = new ZoomScreen(myImg);
_screen = new MainScreen();
_nextScreen = new ButtonField("Go to Next Screen",ButtonField.FIELD_HCENTER | ButtonField.CONSUME_CLICK);
_nextScreen.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field,int context) {
pushScreen(new NextScreen());
}
});
_screen.setTitle(new LabelField("Hello World Demo",LabelField.USE_ALL_WIDTH));
_screen.add(new RichTextField("Hello to the BlackBerry World!",Field.NON_FOCUSABLE));
_screen.add(_nextScreen);
pushScreen(_screen);
pushScreen(zoomableImg);
}
}
//I'm confused about your question. But still I'm posting ans here hope it will help you.
public final class ZoomScreenDemo extends UiApplication
{
public static void main(final String[] args)
{
UiApplication app = new ZoomScreenDemo();
app.enterEventDispatcher();
}
public ZoomScreenDemo()
{
pushScreen(new ZoomScreenDemoScreen());
}
public final static class ZoomScreenDemoScreen extends MainScreen
{
private EncodedImage _image;
private ButtonField _nextScreen;
public ZoomScreenDemoScreen()
{
setTitle("Zoom Screen Demo");
_nextScreen = new ButtonField("Go to next screen ",ButtonField.CONSUME_CLICK);
_nextScreen.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().pushScreen(new DemoZoomScreen(_image));
}
});
add( _nextScreen );
_image = EncodedImage.getEncodedImageResource("img/building.jpg");
BitmapField bitmapField = new BitmapField(_image.getBitmap(), FIELD_HCENTER | FOCUSABLE);
add(bitmapField);
}
}
static class DemoZoomScreen extends ZoomScreen
{
DemoZoomScreen(EncodedImage image)
{
super(image);
}
public void zoomedOutNearToFit()
{
close();
}
}
}

GWT retrieve list from datastore via serviceimpl

Hi I'm trying to retrieve a linkedhashset from the Google datastore but nothing seems to happen. I want to display the results in a Grid using GWT on a page. I have put system.out.println() in all the classes to see where I go wrong but it only shows one and I don't recieve any errors. I use 6 classes 2 in the server package(ContactDAOJdo/ContactServiceImpl) and 4 in the client package(ContactService/ContactServiceAsync/ContactListDelegate/ContactListGui). I hope someone can explain why this isn't worken and point me in the right direction.
public class ContactDAOJdo implements ContactDAO {
#SuppressWarnings("unchecked")
#Override
public LinkedHashSet<Contact> listContacts() {
PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
String query = "select from " + Contact.class.getName();
System.out.print("ContactDAOJdo: ");
return (LinkedHashSet<Contact>) pm.newQuery(query).execute();
}
}
public class ContactServiceImpl extends RemoteServiceServlet implements ContactService{
private static final long serialVersionUID = 1L;
private ContactDAO contactDAO = new ContactDAOJdo() {
#Override
public LinkedHashSet<Contact> listContacts() {
LinkedHashSet<Contact> contacts = contactDAO.listContacts();
System.out.println("service imp "+contacts);
return contacts;
}
}
#RemoteServiceRelativePath("contact")
public interface ContactService extends RemoteService {
LinkedHashSet<Contact> listContacts();
}
public interface ContactServiceAsync {
void listContacts(AsyncCallback<LinkedHashSet <Contact>> callback);
}
public class ListContactDelegate {
private ContactServiceAsync contactService = GWT.create(ContactService.class);
ListContactGUI gui;
void listContacts(){
contactService.listContacts(new AsyncCallback<LinkedHashSet<Contact>> () {
public void onFailure(Throwable caught) {
gui.service_eventListContactenFailed(caught);
System.out.println("delegate "+caught);
}
public void onSuccess(LinkedHashSet<Contact> result) {
gui.service_eventListRetrievedFromService(result);
System.out.println("delegate "+result);
}
});
}
}
public class ListContactGUI {
protected Grid contactlijst;
protected ListContactDelegate listContactService;
private Label status;
public void init() {
status = new Label();
contactlijst = new Grid();
contactlijst.setVisible(false);
status.setText("Contact list is being retrieved");
placeWidgets();
}
public void service_eventListRetrievedFromService(LinkedHashSet<Contact> result){
System.out.println("1 service eventListRetreivedFromService "+result);
status.setText("Retrieved contactlist list");
contactlijst.setVisible(true);
this.contactlijst.clear();
this.contactlijst.resizeRows(1 + result.size());
int row = 1;
this.contactlijst.setWidget(0, 0, new Label ("Voornaam"));
this.contactlijst.setWidget(0, 1, new Label ("Achternaam"));
for(Contact contact: result) {
this.contactlijst.setWidget(row, 0, new Label (contact.getVoornaam()));
this.contactlijst.setWidget(row, 1, new Label (contact.getVoornaam()));
row++;
System.out.println("voornaam: "+contact.getVoornaam());
}
System.out.println("2 service eventListRetreivedFromService "+result);
}
public void placeWidgets() {
System.out.println("placewidget inside listcontactgui" + contactlijst);
RootPanel.get("status").add(status);
RootPanel.get("contactlijst").add(contactlijst);
}
public void service_eventListContactenFailed(Throwable caught) {
status.setText("Unable to retrieve contact list from database.");
}
}
It could be the query returns a lazy list. Which means not all values are in the list at the moment the list is send to the client. I used a trick to just call size() on the list (not sure how I got to that solution, but seems to work):
public LinkedHashSet<Contact> listContacts() {
final PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
try {
final LinkedHashSet<Contact> contacts =
(LinkedHashSet<Contact>) pm.newQuery(Contact.class).execute();
contacts.size(); // this triggers to get all values.
return contacts;
} finally {
pm.close();
}
}
But I'm not sure if this is the best practice...

Resources