I am using JavaFX to create an application. SplashScreen opens properly and sets on the screen even after the application opens.
Here are my codes:
Main Class:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class SplashScreen extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root=FXMLLoader.load(getClass().getResource("SplashScreenFXML.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller Class:
package splashscreen;
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.Application;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class SplashScreenFXMLController implements Initializable
{
#FXML
private AnchorPane rootPane;
#Override
public void initialize(URL url, ResourceBundle rb)
{
new SplashScreen().start();
}
class SplashScreen extends Thread
{
#Override
public void run()
{
try
{
Thread.sleep(5000);
Platform.runLater(new Runnable(){
#Override
public void run()
{
try {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
Stage stage=new Stage();
stage.setScene(scene);
stage.show();
rootPane.getScene().getWindow().hide();
} catch (IOException ex) {
Logger.getLogger(SplashScreenFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} catch (InterruptedException ex) {
Logger.getLogger(SplashScreenFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
can Anybody help me with this?
I think rootPane.getScene().getWindow().hide(); this is not working. Is there any otherway that I can hide the SplashScreen Stage?
Related
import java.time.DayOfWeek;
import java.time.LocalDate;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.VBox;
public class Example extends Application {
#Override public void start(Stage stage) {
VBox container = new VBox();
DatePicker datePicker = new DatePicker();
disableSomeDates(datePicker);
Button disableMondaysButton = new Button("No Mondays!");
disableMondaysButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
disableSomeMoreDates(datePicker);
}
});
container.getChildren().add(datePicker);
container.getChildren().add(disableMondaysButton);
Scene scene = new Scene(container);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public void disableSomeDates(DatePicker datePicker) {
datePicker.setDayCellFactory(param -> new DateCell() {
#Override
public void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
//Disables dates before current date
setDisable(empty || date.compareTo(LocalDate.now()) < 0 );
}
});
}
public void disableSomeMoreDates(DatePicker datePicker) {
datePicker.setDayCellFactory(param -> new DateCell() {
#Override
public void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
//Disables mondays
setDisable(empty || date.getDayOfWeek() == DayOfWeek.MONDAY);
}
});
}
}
In this example code I create a DatePicker and disable some dates (dates before today). Then by pressing the button it should disable Mondays and thus we should have all dates before today and all mondays disabled. In this case we'll end up with only mondays disabled.
How do I make it so that the button disables mondays without re-enabling dates before today?
I'd recommend using a single cell factory, generating cells which observe properties that can then be changed.
E.g.:
import java.time.DayOfWeek;
import java.time.LocalDate;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Example extends Application {
#Override public void start(Stage stage) {
BooleanProperty mondaysDisabled = new SimpleBooleanProperty(false);
VBox container = new VBox();
DatePicker datePicker = new DatePicker();
datePicker.setDayCellFactory(dp -> new DateCell() {
{
mondaysDisabled.addListener((obs, mondaysWereDisabled, mondaysAreNowDisabled)
-> updateDisabledStatus());
}
#Override
public void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
updateDisabledStatus();
}
private void updateDisabledStatus() {
if (isEmpty()) {
setDisable(true);
} else {
LocalDate date = getItem();
if (date.isBefore(LocalDate.now())) {
setDisable(true);
} else {
if (mondaysDisabled.get() && date.getDayOfWeek() == DayOfWeek.MONDAY) {
setDisable(true);
} else {
setDisable(false);
}
}
}
}
});
Button disableMondaysButton = new Button("No Mondays!");
disableMondaysButton.setOnAction(event -> mondaysDisabled.set(true));
container.getChildren().add(datePicker);
container.getChildren().add(disableMondaysButton);
Scene scene = new Scene(container);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
For something of a more modular approach, you could keep an observable list of filters to check. E.g.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.function.Predicate;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Example extends Application {
#Override public void start(Stage stage) {
ObservableList<Predicate<LocalDate>> dayFilters = FXCollections.observableArrayList();
dayFilters.add(date -> date != null);
dayFilters.add(date -> ! date.isBefore(LocalDate.now()));
VBox container = new VBox();
DatePicker datePicker = new DatePicker();
datePicker.setDayCellFactory(dp -> new DateCell() {
{
dayFilters.addListener((Change<? extends Predicate<LocalDate>> change) -> updateDisabledStatus());
}
#Override
public void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
updateDisabledStatus();
}
private void updateDisabledStatus() {
setDisable(false);
for (Predicate<LocalDate> check : dayFilters) {
if (! check.test(getItem())) {
setDisable(true);
break ;
}
}
}
});
Button disableMondaysButton = new Button("No Mondays!");
disableMondaysButton.setOnAction(event -> dayFilters.add(date -> date.getDayOfWeek() != DayOfWeek.MONDAY));
container.getChildren().add(datePicker);
container.getChildren().add(disableMondaysButton);
Scene scene = new Scene(container);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
I have written code to render my html page( html page is from my local machine) in JavaFX application and now I would like to reload webview whenever the html page(specified) gets modified.
And html modification is done by other application.
Can anyone please let me know how to reload the webview .
Here's the my code :
package view;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.Timer;
import java.util.TimerTask;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class ProgressView extends Application {
private Scene scene;
Browser br = new Browser("E:\\Developer-Job\\test.html");
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Web View");
scene = new Scene(br,750,500, Color.web("#666970"));
stage.setScene(scene);
//scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser(String url) {
//apply the styles
getStyleClass().add("browser");
// load the web page
String strXml = "";
String strBuilt ="";
try {
File f = new File(url);
webEngine.load(f.toURI().toURL().toString());
//add the web view to the scene
getChildren().add(browser);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
}
#Override protected double computePrefWidth(double height) {
return 750;
}
#Override protected double computePrefHeight(double width) {
return 500;
}
}
}
Thanks in advance.
What about checking for changes periodically?
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.io.IOException;
public class ProgressView extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.setTitle("Web View");
Browser br = new Browser("E:\\Developer-Job\\test.html");
Scene scene = new Scene(br, 750, 500, Color.web("#666970"));
stage.setScene(scene);
//scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser(String url) {
getChildren().add(browser);
//apply the styles
getStyleClass().add("browser");
// load the web page
String strXml = "";
String strBuilt = "";
load(url);
Timeline timeline = new Timeline(new KeyFrame(
Duration.millis(2500),
ae -> load(url)));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
private void load(String url) {
try {
File f = new File(url);
webEngine.load(f.toURI().toURL().toString());
//add the web view to the scene
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Node createSpacer() {
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
#Override
protected void layoutChildren() {
double w = getWidth();
double h = getHeight();
layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
}
#Override
protected double computePrefWidth(double height) {
return 750;
}
#Override
protected double computePrefHeight(double width) {
return 500;
}
}
}
I've found an answer using below code:
webEngine.documentProperty().addListener(new ChangeListener<Document>() {
#Override
public void changed(ObservableValue<? extends Document> observableValue, Document document, Document newDoc) {
if (newDoc != null) {
//webEngine.documentProperty().removeListener(this);
try {
webEngine.load(f.toURI().toURL().toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
I am having one code that send command to server.
public static void createAndSendCommand(String action, byte[] data) {
if (action.equals(OE_Constants.ACTION_UPDATE)) {
File file = new File(OE_Constants.FILE_BACKUP_TOPOLOGY);
Command command = ConnectionManager.populateData(file);
FrontEndClient.sendCommandToServer(command);
}
}
and
public static boolean sendCommandToServer(Command command) {
try {
outStream.writeObject(command);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
And I am receiving result like below.
public void receiveResultFromServer() {
try {
while(!clientSocket.isClosed()) {
CommandExecResult result;
try {
result = (CommandExecResult) inStream.readObject();
ConnectionManager.parseCommandExecutionResult(result);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now I want to wait for command to be successfully executed on server till the result of it is received by client. I want to show some Progress indicator type of UI ....how to do that?
Thanks!
Use a Task or a Service for your long running server calls.
Use Task.updateProgress() to inform on the current progress / work done.
Bind the progressProperty of your running Task to a ProgressBar or ProgressIndicator.
You specified the tags java and javafx. Here is my solution for javafx. It is a simple dialog that can be updated from 'outside' via binding.
WorkingDialog.java:
package stackoverflow.progress;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
public final class WorkingDialog extends Stage implements Initializable {
private static final Logger LOG = Logger.getLogger(WorkingDialog.class.getName());
public SimpleDoubleProperty progress = new SimpleDoubleProperty(0);
public WorkingDialog(String title, Stage owner) {
super();
setTitle(title);
initStyle(StageStyle.UTILITY);
initModality(Modality.APPLICATION_MODAL);
initOwner(owner);
double w = 300;
double h = 200;
setWidth(w);
setHeight(h);
double dx = (owner.getWidth() - w) / 2;
double dy = (owner.getHeight() - h) / 2;
setX(owner.xProperty().get() + dx);
setY(owner.yProperty().get() + dy);
setResizable(false);
showDialog(progress);
}
public void hideDialog() {
Platform.runLater(() -> {
hide();
});
}
public void setTitleText(String title) {
Platform.runLater(() -> {
setTitle(title);
});
}
private void showDialog(SimpleDoubleProperty progress) {
//scene : gridPane : 0,0->progressbar,0,1->borderpane : center->button
GridPane gridPane = new GridPane();
gridPane.setGridLinesVisible(false);
gridPane.setPadding(new Insets(10));
gridPane.setHgap(5);
gridPane.setVgap(5);
setOnCloseRequest((WindowEvent e) -> {
e.consume();
});
ProgressBar pb = new ProgressBar(-1);
pb.setPrefWidth(300);
pb.progressProperty().bind(progress);
BorderPane borderPane = new BorderPane(pb);
gridPane.add(borderPane, 0, 0);
Scene scene = new Scene(gridPane);
setScene(scene);
sizeToScene();
show();
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
Example for usage (WorkingDialogTest.java):
package stackoverflow.progress;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class WorkingDialogTest extends Application {
private static final Logger LOG = Logger.getLogger(WorkingDialogTest.class.getName());
#Override
public void start(Stage primaryStage) {
Group group = new Group();
Scene scene = new Scene(group);
primaryStage.setTitle("Dialogs");
primaryStage.setWidth(600);
primaryStage.setHeight(400);
Button button = new Button("function");
button.setOnAction((ActionEvent e) -> {
WorkingDialog wd = new WorkingDialog("title", primaryStage);
new Thread(() -> {
int counter = 10;
for (int i = 0; i < counter; i++) {
try {
wd.progress.set(1.0 * i / (counter - 1));
Thread.sleep(1000); //<-------- do more useful stuff here
} catch (InterruptedException ex) {
}
}
wd.hideDialog();
}).start();
});
HBox hbox = new HBox(button);
group.getChildren().addAll(hbox);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
It looks like this:
I am adding button to grid pane dynamically but after giving them function they all show same function and i don't knows why?
import java.awt.Panel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
public class TestController implements Initializable {
#FXML
Panel mpanel;
#FXML
GridPane gpnael;
int x=0,y=0,i=0,y1=0;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void add(ActionEvent event) {
y1++;
Button temp = new Button("Button " + i);
temp.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
System.out.println("button"+y1);
}
});
gpnael.add(temp,i++,1);
}
}
now i have added three button to grid pane when i click on each button they show same output.
I want that they all show different output as assigned .
You are not defining it in the buttons, you are always using a non final int to express your values you should try do make them with unique values or to set an id for each button and get the value from the id:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class ButtonsOnGPanel extends Application {
private int i = 0;
private GridPane gpnael = new GridPane();
#Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
while(i<3){
addButton();
}
root.getChildren().add(gpnael);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
private void addButton() {
i++;
final Button temp = new Button("Button " + i);
final int numButton= i;
temp.setId("" + i);
temp.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
System.out.println("id(" + temp.getId() + ") = " + numButton);
}
});
gpnael.add(temp, i, 1);
}
public static void main(String[] args) {
launch(args);
}
}
And if you want to use lambda expressions:
temp.setOnAction((ActionEvent e) -> {
System.out.println("id(" + temp.getId() + ") = " + numButton);
});
The scrollTo method in the code below works really slow. Is there any way to speed up it or may be some alternative variant? I need to display almost 100000 items in the application. Probably there are some alternative components. Thanks.
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
final ListView<String> listView = new ListView<>();
Button button = new Button("goto");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
int i = 99998;
System.out.println("before scroll");
long startTime = System.currentTimeMillis();
listView.scrollTo(i);
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println(elapsedTime);
listView.getFocusModel().focus(i);
}
});
List<String> items = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
items.add(UUID.randomUUID().toString());
}
listView.setItems(FXCollections.observableArrayList(items));
StackPane pane = new StackPane();
VBox vbox = new VBox();
vbox.getChildren().add(button);
vbox.getChildren().add(listView);
pane.getChildren().add(vbox);
stage.setScene(new Scene(pane));
stage.show();
}
}