Make a draggable popup background transparent in javafx? - popup

I'm doing a little excersice i JavaFX with netbeans, I'm trying to make a popup when I clic a button, but the popup have a white background, how can I do it transparent?
Thanks.
Here is the code:
Main:
package test;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.image.Image;
public class Test extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.TRANSPARENT);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root, Color.TRANSPARENT);
stage.setScene(scene);
stage.show();
stage.setTitle("integrIX");
stage.getIcons().add(new Image("test/integrix_icon.png"));
}
public static void main(String[] args) {
launch(args);
}
}
FXMLController:
package test;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class FXMLDocumentController implements Initializable {
#FXML
private Button menu1;
#FXML
private Button menu2;
#FXML
private Button menu3;
#FXML
private Button menu4;
#FXML
private Button closeButton;
#FXML
private Button minimizeButton;
#FXML
private Pane paneMain;
private double xOffset;
private double yOffset;
private Stage popup;
#Override
public void initialize(URL url, ResourceBundle rb) {
Platform.runLater(new Runnable(){
private StageStyle Color;
#Override
public void run(){
Stage stage = Stage.class.cast(paneMain.getScene().getWindow());
makeDraggable(stage, paneMain);
Parent popupLoaded = null;
try {
popupLoaded = FXMLLoader.load(getClass().getResource("popup.fxml"));
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
Scene popupScene = new Scene(popupLoaded);
popup = new Stage();
popup.initStyle(StageStyle.TRANSPARENT);
popup.initModality(Modality.WINDOW_MODAL);
popup.initOwner(stage);
popup.setScene(popupScene);
}
});
}
#FXML
public void diagnosticButton(){
assert popup != null;
popup.show();
}
#FXML
public void handleClick(MouseEvent event) {
//System.err.println("BOUND OFFSET");
//xOffset = event.getSceneX();
//yOffset = event.getSceneY();
//xOffset = event.getSceneX();
//yOffset = event.getSceneY();
}
#FXML
public void handleDrag(MouseEvent event) {
//System.err.println("DRAGGING");
Stage stage = Stage.class.cast(paneMain.getScene().getWindow());
stage.setX(event.getScreenX() - xOffset);
stage.setY(event.getScreenY() - yOffset);
}
public void makeDraggable( final Stage stage, final Node byNode) {
byNode.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
xOffset = stage.getX() - mouseEvent.getScreenX();
yOffset = stage.getY() - mouseEvent.getScreenY();
byNode.setCursor(Cursor.MOVE);
}
});
byNode.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
byNode.setCursor(Cursor.DEFAULT);
}
});
byNode.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
stage.setX(mouseEvent.getScreenX() + xOffset);
stage.setY(mouseEvent.getScreenY() + yOffset);
} });
byNode.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
} } });
byNode.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
} } });
}
#FXML
public void changeButtonOnOver(Event e){
menu1.getStyleClass().add("boton_over");
}
#FXML
public void changeButtonOnExited(){
menu1.getStyleClass().remove("boton_over");
}
#FXML
public void changeButtonOnOver2(Event e){
menu2.getStyleClass().add("boton_over");
}
#FXML
public void changeButtonOnExited2(){
menu2.getStyleClass().remove("boton_over");
}
#FXML
public void changeButtonOnOver3(Event e){
menu3.getStyleClass().add("boton_over");
}
#FXML
public void changeButtonOnExited3(){
menu3.getStyleClass().remove("boton_over");
}
#FXML
public void changeButtonOnOver4(Event e){
menu4.getStyleClass().add("boton_over");
}
#FXML
public void changeButtonOnExited4(){
menu4.getStyleClass().remove("boton_over");
}
#FXML
public void changeButtonOnOverClose(){
closeButton.getStyleClass().add("btn_cerrar_over");
}
#FXML
public void changeButtonOnExitedClose(){
closeButton.getStyleClass().remove("btn_cerrar_over");
}
#FXML
public void changeButtonOnOverMinimize(){
minimizeButton.getStyleClass().add("btn_cerrar_over");
}
#FXML
public void changeButtonOnExitedMinimize(){
minimizeButton.getStyleClass().remove("btn_cerrar_over");
}
#FXML
public void exit(){
Stage stage = Stage.class.cast(closeButton.getScene().getWindow());
stage.close();
}
#FXML
public void minimize(){
Stage stage = Stage.class.cast(minimizeButton.getScene().getWindow());
stage.setIconified(true);
}
}
Popup Controller:
package test;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class PopupController implements Initializable {
#FXML
private Pane rect;
private double xOffset;
private double yOffset;
#Override
public void initialize(URL url, ResourceBundle rb) {
Platform.runLater(new Runnable(){
private Parent root;
#Override
public void run(){
Stage stage = Stage.class.cast(rect.getScene().getWindow());
makeDraggable(stage, rect);
}});
}
#FXML
public void initialize(){
System.err.println("init popup called");
assert rect != null;
Stage stage = Stage.class.cast(rect.getScene().getWindow());
makeDraggable(stage, rect);
}
public void makeDraggable( final Stage stage, final Node byNode) {
byNode.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
xOffset = stage.getX() - mouseEvent.getScreenX();
yOffset = stage.getY() - mouseEvent.getScreenY();
byNode.setCursor(Cursor.MOVE);
}
});
byNode.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
byNode.setCursor(Cursor.DEFAULT);
}
});
byNode.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
stage.setX(mouseEvent.getScreenX() + xOffset);
stage.setY(mouseEvent.getScreenY() + yOffset);
} });
byNode.setOnMouseEntered(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
} } });
byNode.setOnMouseExited(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent mouseEvent) {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
} } });
}
#FXML
private Button closeButton;
#FXML
public void changeButtonOnOverClose(){
closeButton.getStyleClass().add("btn_cerrar_over");
}
#FXML
public void changeButtonOnExitedClose(){
closeButton.getStyleClass().remove("btn_cerrar_over");
}
#FXML
public void exit(){
Stage stage = Stage.class.cast(closeButton.getScene().getWindow());
stage.close();
}
}

In Popup Controller initialize try:
rect.setStyle("-fx-background-color: transparent;");

Related

Gwt-platform with UiBinder and UiEditors Framework (GWT Editors)

I struggle with Editor framework of gwt. Mostly because the documentation is lame- no hurt feelings- just saying.
Now I have problem that I cannot execute button event on editor. This is my error:
Uncaught com.google.gwt.event.shared.UmbrellaException: Exception caught: (TypeError) : Cannot read property 'onLoginButtonClick_3_g$' of undefined
I am not sure what I am doing wrong. I didn't found any good example of that. I hope someone will help.
Here is my code:
Editor
public class LoginEditor extends ViewWithUiHandlers<LoginEditorUiHandlers> implements Editor<LoginModel> {
private VerticalPanel widget = new VerticalPanel();
MaterialTextBox email = new MaterialTextBox();
MaterialTextBox password = new MaterialTextBox();
MaterialButton btnLogin = new MaterialButton();
public LoginEditor() {
initWidget(widget);
email.setPlaceholder("E-mail");
password.setPlaceholder("Password");
btnLogin.setText("Login");
btnLogin.addClickHandler(new ClickHandler() {
#Override public void onClick(ClickEvent event) {
onLoginButtonClick(event);
}
});
widget.add(email);
widget.add(password);
widget.add(btnLogin);
}
void onLoginButtonClick(ClickEvent e){
getUiHandlers().onLoginButtonClick();
Window.alert("TEST");
}
}
Presenter
public class LoginPresenter extends Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> implements LoginEditorUiHandlers {
public interface MyView extends View , HasUiHandlers<LoginEditorUiHandlers> {}
public static final Type<RevealContentHandler<?>> SLOT_Login = new Type<RevealContentHandler<?>>();
#ProxyStandard
#NameToken(NameTokens.login)
public interface MyProxy extends ProxyPlace<LoginPresenter> {}
// Editor
interface Driver extends SimpleBeanEditorDriver<LoginModel, LoginEditor> {}
private static final LoginService service = GWT.create(LoginService.class);
Driver editorDriver = GWT.create(Driver.class);
private LoginModel model = new LoginModel("email","pass");
private LoginEditor editor = new LoginEditor();
#Override
public void onLoginButtonClick() {
MaterialToast.fireToast("TEST");
try{
System.out.println(editorDriver == null);
System.out.println(editorDriver.isDirty());
editorDriver.isDirty();
} catch (NullPointerException e) {
MaterialToast.fireToast("Null: " + e.getLocalizedMessage());
}
if (editorDriver.isDirty()) {
model = editorDriver.flush();
if (editorDriver.hasErrors()) {
StringBuilder errorBuilder = new StringBuilder();
for (EditorError error : editorDriver.getErrors()) {
errorBuilder.append(error.getMessage() + "\n");
}
MaterialToast.fireToast(errorBuilder.toString());
} else {
service.login(
model, new MethodCallback<Integer>() {
#Override
public void onSuccess(Method method, Integer response) {
MaterialToast.fireToast("Succefully set info. status code: " + response);
}
#Override
public void onFailure(Method method, Throwable exception) {
MaterialToast.fireToast("Error setting");
}
});
}
} else {
MaterialToast.fireToast("Data has not changed");
}
}
#Inject
LoginPresenter(
EventBus eventBus,
MyView view,
MyProxy proxy) {
super(eventBus, view, proxy, RevealType.Root);
editorDriver.initialize(editor);
editorDriver.edit(model);
getView().setUiHandlers(this);
}
}
View
public class LoginView extends ViewWithUiHandlers<LoginEditorUiHandlers> implements LoginPresenter.MyView {
interface Binder extends UiBinder<Widget, LoginView> {
}
#Inject
LoginView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
}
View.ui.xml
<m:MaterialRow ui:field="loginWidget">
<m:MaterialColumn grid="s12 m4 l4" offset="l4" >
<m:MaterialTitle title="Login" description="Please provide your account credentials."/>
<m:MaterialPanel padding="5" shadow="1" addStyleNames="{style.panel}">
<m:MaterialPanel addStyleNames="{style.fieldPanel}">
<e:LoginEditor></e:LoginEditor>
</m:MaterialPanel>
</m:MaterialPanel>
</m:MaterialColumn>
</m:MaterialRow>
UiHandlers
interface LoginEditorUiHandlers extends UiHandlers {
void onLoginButtonClick();
}
interface LoginUiHandlers extends UiHandlers {
}
Here is working solution:
Presenter
package pl.korbeldaniel.cms.client.login;
import java.util.ArrayList;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import gwt.material.design.client.ui.MaterialToast;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.HasUiHandlers;
import pl.korbeldaniel.cms.client.editor.BeanEditView;
import pl.korbeldaniel.cms.client.model.LoginModel;
import pl.korbeldaniel.cms.client.place.NameTokens;
import pl.korbeldaniel.cms.client.service.LoginService;
public class LoginPresenter extends Presenter<LoginPresenter.MyView, LoginPresenter.MyProxy> implements LoginUiHandlers {
public interface MyView extends BeanEditView<LoginModel>, HasUiHandlers<LoginUiHandlers> {}
public static final Type<RevealContentHandler<?>> SLOT_Login = new Type<RevealContentHandler<?>>();
#ProxyStandard
#NameToken(NameTokens.login)
public interface MyProxy extends ProxyPlace<LoginPresenter> {}
// Editor
private SimpleBeanEditorDriver<LoginModel, ?> editorDriver;
private static final LoginService service = GWT.create(LoginService.class);
private LoginModel model = new LoginModel("","");
#Override
public void onLoginButtonClick() {
String msg = "User Pressed a button.";
GWT.log(msg);
if (editorDriver.isDirty()) {
model = editorDriver.flush();
validateModel();
GWT.log(String.valueOf(editorDriver.hasErrors()));
if (editorDriver.hasErrors()) {
MaterialToast.fireToast("Errors occur");
StringBuilder errorBuilder = new StringBuilder();
for (EditorError error : editorDriver.getErrors()) {
GWT.log(error.getMessage());
errorBuilder.append(error.getMessage() + "\n");
}
//MaterialToast.fireToast(errorBuilder.toString());
RootPanel.get().add(new Label(errorBuilder.toString()));
} else {
service.login(
model, new MethodCallback<Integer>() {
#Override
public void onSuccess(Method method, Integer response) {
MaterialToast.fireToast("Succefully set info. status code: " + response);
}
#Override
public void onFailure(Method method, Throwable exception) {
MaterialToast.fireToast("Error setting");
}
});
}
} else {
MaterialToast.fireToast("Data has not changed");
}
}
private void validateModel() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<LoginModel>> violations = validator.validate(model);
GWT.log(String.valueOf(violations.size()));
if (violations.size() > 0) {
editorDriver.setConstraintViolations(new ArrayList<ConstraintViolation<?>>(violations));
}
}
#Inject
LoginPresenter(EventBus eventBus,MyView view, MyProxy proxy) {
super(eventBus, view, proxy, RevealType.Root);
getView().setUiHandlers(this);
editorDriver = getView().createEditorDriver();
editorDriver.edit(model);
}
}
View/Editor
package pl.korbeldaniel.cms.client.login;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialCheckBox;
import gwt.material.design.client.ui.MaterialTextBox;
import javax.inject.Inject;
import pl.korbeldaniel.cms.client.model.LoginModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
public class LoginView extends ViewWithUiHandlers<LoginUiHandlers> implements LoginPresenter.MyView {
interface Binder extends UiBinder<Widget, LoginView> {}
/** The driver to link the proxy bean with the view. */
public interface EditorDriver extends SimpleBeanEditorDriver<LoginModel, LoginView> { }
#UiField MaterialTextBox email;
#UiField MaterialTextBox password;
#UiField MaterialButton loginButton;
#UiField MaterialCheckBox keepMeLoggedInCheckbox;
#Inject
LoginView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
addClickHandlerToLoginButton();
}
//#UiHandler("loginButton")
private void onLoginButtonClick(ClickEvent e){
getUiHandlers().onLoginButtonClick();
}
private void addClickHandlerToLoginButton() {
loginButton.addClickHandler(new ClickHandler() {
#Override public void onClick(ClickEvent event) {
onLoginButtonClick(event);
}
});
}
#Override
public SimpleBeanEditorDriver<LoginModel, ?> createEditorDriver() {
EditorDriver driver = GWT.create(EditorDriver.class);
driver.initialize(this);
return driver;
}
}
ValidatorFactory
package pl.korbeldaniel.cms.client.login;
import javax.validation.Validator;
import pl.korbeldaniel.cms.client.model.LoginModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.validation.client.AbstractGwtValidatorFactory;
import com.google.gwt.validation.client.GwtValidation;
import com.google.gwt.validation.client.impl.AbstractGwtValidator;
public final class SampleValidatorFactory extends AbstractGwtValidatorFactory {
/**
* Validator marker for the Validation Sample project. Only the classes and
* groups listed in the {#link GwtValidation} annotation can be validated.
*/
#GwtValidation(LoginModel.class)
public interface GwtValidator extends Validator {
}
#Override
public AbstractGwtValidator createValidator() {
return GWT.create(GwtValidator.class);
}
}
UiHandlers
package pl.korbeldaniel.cms.client.login;
import com.gwtplatform.mvp.client.UiHandlers;
interface LoginUiHandlers extends UiHandlers {
void onLoginButtonClick();
}
Bean edit view interface
package pl.korbeldaniel.cms.client.editor;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.gwtplatform.mvp.client.View;
/**
* Implemented by views that edit beans.
*
* #param <B> the type of the bean
*/
public interface BeanEditView<B> extends View, Editor<B> {
/**
* #return a new {#link SimpleBeanEditorDriver} initialized to run this editor
*/
SimpleBeanEditorDriver<B, ?> createEditorDriver();
}
I hope it will help some one.

Eclipse error com.avaje.ebean.EbeanServer not resolved

In Eclipse I have an error on my top blank line and I cant get rid of it. Here's my code (I am making a bukkit plugin):
//this is where I get the error
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new EventHandler(this);
}
#Override
public void onDisable() {
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("BLANK") && sender instanceof Player) {
Player player = (Player) sender;
return true;
}
return false;
}
}
I can't find anyway around it. Please help.
You appear to be missing your package name. Try this instead:
package my.package.name;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new EventHandler(this);
}
#Override
public void onDisable() {
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("BLANK") && sender instanceof Player) {
Player player = (Player) sender;
return true;
}
return false;
}
}
Remember to replace my.package.name with your package name.

Launch JavaFX application from another class

I need to start a javafx Application from another "container" class and call functions on the Application, but there doesn't seem to be any way of getting hold of a reference to the Application started using the Application.launch() method. Is this possible?
Thanks
Suppose this is our JavaFX class:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class OKButton extends Application {
#Override
public void start(Stage stage) {
Button btn = new Button("OK");
Scene scene = new Scene(btn, 200, 250);
stage.setTitle("OK");
stage.setScene(scene);
stage.show();
}
}
Then we may launch it from another class like this:
import javafx.application.Application;
public class Main {
public static void main(String[] args) {
Application.launch(OKButton.class, args);
}
}
I had the same problem as this and got round it using this hack:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.concurrent.CountDownLatch;
public class StartUpTest extends Application {
public static final CountDownLatch latch = new CountDownLatch(1);
public static StartUpTest startUpTest = null;
public static StartUpTest waitForStartUpTest() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return startUpTest;
}
public static void setStartUpTest(StartUpTest startUpTest0) {
startUpTest = startUpTest0;
latch.countDown();
}
public StartUpTest() {
setStartUpTest(this);
}
public void printSomething() {
System.out.println("You called a method on the application");
}
#Override
public void start(Stage stage) throws Exception {
BorderPane pane = new BorderPane();
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
Label label = new Label("Hello");
pane.setCenter(label);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
and then the class you are launching the application from:
public class StartUpStartUpTest {
public static void main(String[] args) {
new Thread() {
#Override
public void run() {
javafx.application.Application.launch(StartUpTest.class);
}
}.start();
StartUpTest startUpTest = StartUpTest.waitForStartUpTest();
startUpTest.printSomething();
}
}
Hope that helps you.
Launch JavaFX in other Class using Button:
class Main extends Application{
public void start(Stage s)throws Exception{
event();
s.show();
}
public void event(){
btn.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ae){
Stage s = new Stage();
new SubClassName().start(s);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
class SubClassName{
public void start(Stage s){
Pane pane = new Pane();
Scene addFrame = new Scene(pane,280,450);
s.setScene(addFrame);
s.show();
}
}
I'm not sure what you're trying to achieve, but note that you can e.g call from another class Application.launch to start the JavaFX Application thread and Platform.exit to stop it.
The above ways of invoking other javafx class from another sometimes work. Struggling to find an ultimate way to do this brought me to the following walk around:
Suppose this is the javafx class that exteds Application we wish to show from a different class, then we should add the following lines
class ClassToCall extends Application{
//Create a class field of type Shape preferably static...
static Stage classStage = new Stage();
#Override
public void start(Stage primaryStage){
// Assign the class's stage object to
// the method's local Stage object:
classStage = primaryStage ;
// Here comes some more code that creates a nice GUI.....
// ......
}
}
And now from the other place in the project, in order to open the window
that the above class creates do the following:
// Suppose we want to do it with a button clicked:
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//create an object of the class you wish to invoke its
//start() method:
ClassToCall ctc = new ClassToCall();
// Then call its start() method in the following way:
ctc.start(ClassToCall.classStage);
}// End handle(ActionEvent event)
});// End anonymous class

Customized itemreader throwing ReaderNotOpenException

I have a customized item reader as shown below
class MyReader implements ItemReader<MyBean>, ItemStream{
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader;
public SingleItemPeekableItemReader<MyBean> getMyBeanPeekableReader() {
return myBeanPeekableReader;
}
public void setMyBeanPeekableReader(
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader) {
this.myBeanPeekableReader = myBeanPeekableReader;
}
#Resource
public void caller(ItemReader<MyBean> myJdbcReader){
myBeanPeekableReader.setDelegate(myJdbcReader);
}
#Override
public void close() throws ItemStreamException {
myBeanPeekableReader.close();
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
myBeanPeekableReader.open(arg0);
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
// TODO Auto-generated method stub
}
Class extending JdbcCursorItemReader:
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("myJdbcReader")
public class MyJdbcReader extends JdbcCursorItemReader<MyBean> {
private String sql = "Select * from mytable";
MyJdbcReader(){
super.setSql(sql);
}
#Override
#Resource
public void setDataSource(DataSource dataSource){
super.setDataSource(dataSource);
}
#Override
#Resource
public void setRowMapper(RowMapper myRowMapper){
super.setRowMapper(myRowMapper);
}
#Override
#Resource
public void setPreparedStatementSetter(PreparedStatementSetter myPrepSetter){
super.setPreparedStatementSetter(myPrepSetter);
}
}
Even after implementing ItemStream it is throwing exception ReaderNotFound..can someone suggest where I am getting wrong.

How to listen for WindowEvent.WINDOW_SHOWN in the nodes of the scene graph?

It seems WindowEvent.WINDOW_SHOWN never gets dispatched on any of the nodes in the scene graph, nor is there anyway (that I could find) to know when a node is visible/rendered/shown. For example:
TestLauncher.java
package com.example.javafx.event;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TestLauncher extends Application
{
public static void main(String[] args)
{
Application.launch(TestLauncher.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load(TestController.class.getResource("TestView.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
}
TestController.java
package com.example.javafx.event;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.TextField;
import javafx.stage.WindowEvent;
public class TestController implements Initializable
{
#FXML private Parent root;
#FXML private TextField serverAddressInput;
#FXML private TextField usernameInput;
#Override
public void initialize(URL url, ResourceBundle rb)
{
serverAddressInput.setText("127.0.0.1");
//won't work because stage isn't visible yet
trySetFocusOnUsernameInput1();
//apparently Stage never passes on any WindowEvents to the children...
trySetFocusOnUsernameInput2();
}
private void trySetFocusOnUsernameInput1()
{
usernameInput.requestFocus();
}
private void trySetFocusOnUsernameInput2()
{
root.addEventFilter(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent window)
{
usernameInput.requestFocus();
}
});
root.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent window)
{
usernameInput.requestFocus();
}
});
}
public void handleWindowShownEvent()
{
usernameInput.requestFocus();
}
}
TestView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:id="root"
fx:controller="com.example.javafx.event.TestController"
prefHeight="150"
prefWidth="200"
>
<children>
<TextField fx:id="serverAddressInput" />
<TextField fx:id="usernameInput" />
</children>
</VBox>
So, actually, how else can a node become aware of the fact that it's visible/rendered/shown?
I guess one of the possible solutions is to add the following method to TestController.java
public void handleWindowShownEvent()
{
usernameInput.requestFocus();
}
and then change the start method in TestLauncher to the following:
#Override
public void start(Stage stage) throws Exception
{
FXMLLoader loader = new FXMLLoader();
Parent root = (Parent)loader.load(TestController.class.getResourceAsStream("TestView.fxml"));
final TestController controller = (TestController)loader.getController();
stage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent window)
{
controller.handleWindowShownEvent();
}
});
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
I would really welcome other solutions as this one seems too clunky...
Another solution that admittedly isn't very sexy but decouples the node from the application:
root.sceneProperty().addListener(new ChangeListener<Scene>() {
#Override
public void changed(ObservableValue<? extends Scene> observable, Scene oldValue, Scene newValue) {
newValue.windowProperty().addListener(new ChangeListener<Window>() {
#Override
public void changed(ObservableValue<? extends Window> observable, Window oldValue, Window newValue) {
newValue.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent event) {
usernameInput.requestFocus();
}
});
}
});
}
});
Made more sense in my case.