Error in scene in Java FX - javafx-8

I'm new to javaFX 8 and working with a simple project, but im having some issues with scene.
I get this error:
Error:(35, 25) java: method getScene in class javafx.stage.Window cannot be applied to given types;
required: no arguments
found: javafx.scene.Scene
reason: actual and formal argument lists differ in length
And this is the code:
package ch.makery.address;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MainApp extends Application{
private Stage primaryStage;
private BorderPane rootLayout;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
initRootLayout();
showPersonOverview();
}
public void initRootLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.getScene(scene);
primaryStage.show();
}catch (IOException e) {
e.printStackTrace();
}
}
public void showPersonOverview() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view.Personview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
rootLayout.setCenter(personOverview);
}catch (IOException e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
Thanks in advance.

Related

How to archive processed file in Multi-threaded Step in Spring batch?

I'm using multi-threaded step while reading a file from the resources. Let's say I have several files to be processed & multiple-threads are processing the same file so, I'm not sure at which point in time my whole files get processed.
Once my file successfully processed, I need to archive/delete the file. Can someone guide me what should I use?
Here is my sample code.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Stream;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.AfterStep;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import com.iana.spring.batch.dao.GenericDAO;
import com.iana.spring.batch.listener.BatchJobCompletionListener;
#Configuration
public class BatchConfig {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private JobLauncher jobLauncher;
#Autowired
private Job processJob;
#Value("classpath*:/final/HYUMER_SI_*.txt")
private Resource[] inputFiles;
#Autowired
#Qualifier("test2DataSource")
private DataSource test2DataSource;
public void saveFileLog(String fileLog) throws Exception{
String query = "INSERT INTO FILE_LOG(LOG_INFO) VALUES (?)";
new GenericDAO().saveOrUpdate(test2DataSource, query, false, fileLog);
}
// This job runs in every 5 seconds
//#Scheduled(fixedRate = 150000000)
public void fixedRatedCallingMethod() {
try {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(processJob, jobParameters);
System.out.println("I have been scheduled with Spring scheduler");
} catch (Exception e) {
e.printStackTrace();
}
}
/* In case of multiple DataSources configuration- we need to add following code.
* - It is a good practice to provide Spring Batch database as #Primary to get the benefits of all default functionalities
* implemented by Spring Batch Statistics.
* - All insert and update batch job running statistics will be maintained by Spring Batch Itself.
* - No need to write any extra line of codes.
* Error: To use the default BatchConfigurer the context must contain no more than one DataSource, found 2
*/
#Bean
BatchConfigurer configurer(#Qualifier("testDataSource") DataSource dataSource){
return new DefaultBatchConfigurer(dataSource);
}
#Bean
public Job processJob() throws Exception{
return jobBuilderFactory.get("processJob")
.incrementer(new RunIdIncrementer())
.listener(listener())
.flow(orderStep1())
.end()
.build();
}
#Bean
public TaskExecutor taskExecutor(){
SimpleAsyncTaskExecutor asyncTaskExecutor=new SimpleAsyncTaskExecutor("spring_batch");
asyncTaskExecutor.setConcurrencyLimit(20);
return asyncTaskExecutor;
}
#Bean
public ItemReader<String> batchItemReader() {
Queue<String> dataList = new LinkedList<String>();
return new ItemReader<String>() {
#BeforeStep
public void beforeStep(StepExecution stepExecution) {
System.err.println("in before step...");
try {
if(inputFiles != null) {
for (int i = 0; i < inputFiles.length; i++) {
String fileName = inputFiles[i].getFile().getAbsolutePath();
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach( s -> dataList.add(s));
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("fileList Size::"+dataList.size());
}
#Override
public synchronized String read()throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
System.out.println("--> in item reader.........");
String fileName = null;
if (dataList.size() > 0) {
fileName = dataList.remove();
file_reading_cnt++;
}
return fileName;
}
#AfterStep
public void afterStep(StepExecution stepExecution) {
System.err.println("in after step..."+file_reading_cnt);
}
};
}
volatile int file_reading_cnt = 0;
#Bean
public ItemWriter<String> batchItemWriter(){
return new ItemWriter<String>() {
#Override
public void write(List<? extends String> fileList) throws Exception {
System.out.println("----- in item writer.........");
fileList.forEach(data -> {
try {
saveFileLog(data);
} catch (Exception e) {
e.printStackTrace();
}
});
}
};
}
/**
* To create a step, reader, processor and writer has been passed serially
*
* #return
*/
#Bean
public Step orderStep1() throws Exception{
return stepBuilderFactory.get("orderStep1").<String, String>chunk(20)
.reader(batchItemReader())
.writer(batchItemWriter())
.taskExecutor(taskExecutor())
.throttleLimit(20)
.build();
}
#Bean
public JobExecutionListener listener() {
return new BatchJobCompletionListener();
}
#Bean
public ResourcelessTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
}

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.

Using Selenium how I Print the shipping rate on the checkout page

I want to print the Shipping rate those come on the checkout process, Shipping is calculated dynamically, on the bases of address or may be product in the Cart. I want to print the Shipping rate those come on the 2nd checkout page after calculation.
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.regex.Pattern;
public class testing {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://testing-671.myshopify.com/");
selenium.start();
}
#Test
public void testtesting() throws Exception {
selenium.open("/");
selenium.click("link=Testing");
selenium.waitForPageToLoad("30000");
selenium.click("//a[contains(text(),'Catalog')]");
selenium.waitForPageToLoad("30000");
selenium.click("css=img[alt=\"testing\"]");
selenium.waitForPageToLoad("30000");
selenium.click("id=add-to-cart");
selenium.waitForPageToLoad("30000");
selenium.click("id=checkout");
selenium.waitForPageToLoad("30000");
selenium.type("id=checkout_email", "tester#gmail.com");
selenium.type("id=checkout_shipping_address_first_name", "test");
selenium.type("id=checkout_shipping_address_last_name", "test");
selenium.type("id=checkout_shipping_address_company", "test");
selenium.type("id=checkout_shipping_address_address1", "test");
selenium.type("id=checkout_shipping_address_address2", "test");
selenium.type("id=checkout_shipping_address_city", "test");
selenium.select("id=checkout_shipping_address_country", "label=Albania");
selenium.click("css=option[value=\"Albania\"]");
selenium.select("id=checkout_shipping_address_country", "label=India");
selenium.select("id=checkout_shipping_address_province", "label=Chandigarh");
selenium.type("id=checkout_shipping_address_zip", "160062");
selenium.click("name=commit");
selenium.waitForPageToLoad("30000");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
This is the updated code that I've retrieved by running in Selenium IDE and exporting the testcase as program for Selenium RC and junit:
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.regex.Pattern;
public class Testcases {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://testing-671.myshopify.com");
selenium.start();
}
#Test
public void testCases() throws Exception {
selenium.open("/");
selenium.click("link=Testing");
selenium.waitForPageToLoad("");
selenium.click("//a[contains(text(),'Catalog')]");
selenium.waitForPageToLoad("30000");
selenium.click("css=img[alt=\"testing\"]");
selenium.waitForPageToLoad("30000");
selenium.click("id=add-to-cart");
selenium.waitForPageToLoad("30000");
selenium.click("id=checkout");
selenium.waitForPageToLoad("30000");
selenium.type("id=checkout_email", "tester#gmail.com");
selenium.type("id=checkout_shipping_address_first_name", "test");
selenium.type("id=checkout_shipping_address_last_name", "test");
selenium.type("id=checkout_shipping_address_company", "test");
selenium.type("id=checkout_shipping_address_address1", "test");
selenium.type("id=checkout_shipping_address_address2", "test");
selenium.type("id=checkout_shipping_address_city", "test");
selenium.select("id=checkout_shipping_address_country", "label=Albania");
selenium.select("id=checkout_shipping_address_province", "label=Chandigarh");
selenium.type("id=checkout_shipping_address_zip", "160062");
selenium.click("name=commit");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("//span[#class='total-line__name' and contains(text(),'Shipping')]/following-sibling::strong[contains(text(),'Rs.')]")) break; } catch (Exception e) {}
Thread.sleep(1000);
}
String Price = selenium.getText("//span[#class='total-line__name' and contains(text(),'Shipping')]/following-sibling::strong");
System.out.println(Price);
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}

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

Make a draggable popup background transparent in javafx?

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;");