Opening different websites in JavaFX WebView (Update UI?) - javafx

I'm trying to load different urls into a javafx webview after a given time. I have searched for a solution for at least 2 weeks but i wasn't able to find anything or wasn't able to transfer the solutions of similar problems to my code. Below are the necessary parts of the code:
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/application/FXML.fxml"));
primaryStage.setTitle("Window");
primaryStage.setScene(new Scene (root));
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
FXMLController.java
package application;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class FXMLController implements Initializable {
#FXML private Button btnAddUrl;
#FXML private Button btnStart;
#FXML private Slider sliderTime2NextUrl;
#FXML private WebView webviewWindow;
private WebEngine engine;
private FileChooser fileChooser;
private List<String> url;
private int urlTime;
public void initialize(URL arg0, ResourceBundle arg1) {
btnAddUrl.setOnAction(this::addUrls);
btnStart.setOnAction(this::urlLoad);
fileChooser = new FileChooser();
engine = webviewWindow.getEngine();
getsliderTime2NextUrl();
}//initialize
#FXML
private void addUrls(ActionEvent event) {
fileChooser.setTitle("Add Like List");
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("TXT Files", "*.TXT"),
new ExtensionFilter("txt Files", "*.txt"));
File file = fileChooser.showOpenDialog(null);
try {
url = Files.readAllLines(file.toPath());
} catch (Exception e) {
System.out.println("shit");
}
System.out.println(url);
}
#FXML
private void getsliderTime2NextUrl() {
sliderTime2NextUrl.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("Slider Value Changed (newValue: " + newValue.intValue() + ")");
double getTime;
getTime = sliderTime2NextUrl.valueProperty().getValue();
urlTime = (int) getTime;
}//changed
});//addListener
}//getsliderTime2NextUrl
#FXML
private void urlLoad (ActionEvent event) {
Task<Void> task = new Task<Void>() {
#Override protected Void call() throws Exception{
urlTime = urlTime * 1000 ;
System.out.println("next Url in: " + urlTime);
for(int i = 0; i < url.size(); i++) {
System.out.println("Url.size = "+ url.size());
System.out.println("Url = "+ i);
if(isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + i);
updateProgress(i, 1000);
try {
Thread.sleep(urlTime);
System.out.println("Thread Sleeps for :" + urlTime);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return null;
}
};
new Thread(task).start();
}
/*
#FXML
private void urlLoad (ActionEvent event) {
urlTime = urlTime * 1000 ;
System.out.println("next Url in: " + urlTime);
for(int i = 0; i < url.size(); i++) {
System.out.println("Url.size = "+ url.size());
System.out.println("Url = "+ i);
String Link = url.get(i);
engine.load(Link);
System.out.println("Url loaded = " + Link);
}
}*/
}
FXML.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.web.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="1.7976931348623157E308"
maxWidth="1.7976931348623157E308"
minHeight="400.0" minWidth="500.0"
prefHeight="500.0" prefWidth="500.0"
xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="application.FXMLController">
<children>
<MenuBar maxHeight="25.0" maxWidth="1920.0" prefHeight="25.0" prefWidth="500.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
<Button fx:id="btnAddUrl" layoutX="66.0" layoutY="39.0" mnemonicParsing="false" onAction="#addUrls" prefHeight="25.0" prefWidth="69.0" text="AddUrl" />
<Button fx:id="btnStart" layoutX="36.0" layoutY="108.0" mnemonicParsing="false" onAction="#urlLoad" prefHeight="31.0" prefWidth="108.0" text="Start!">
<font>
<Font size="18.0" />
</font>
</Button>
<Slider fx:id="sliderTime2NextUrl" blockIncrement="1.0" layoutX="204.0" layoutY="39.0" majorTickUnit="2.0" max="15.0" min="3.0" minorTickCount="1" prefHeight="38.0" prefWidth="251.0" showTickLabels="true" showTickMarks="true" snapToTicks="true" value="3.0" />
<WebView fx:id="webviewWindow" layoutY="147.0" minHeight="-1.0" minWidth="-1.0" prefHeight="350.0" prefWidth="500.0" />
</children>
</AnchorPane>
I used the second "urlLoad"-Method (FXMLController.java) in the /* */ first but recognized that all Links are loaded immediately and only the last one stays active. After that I added "Thread.sleep(urlTime) + try & catch" but it freezed my whole GUI until the last URL was loaded. While searching for a solution, that was the first time I heard of workers, tasks & services.
I found out why this happened and tried to add a "Task" around the code. It was a long jorney until I found the code of the first "urlLoad"-Method in FXMLController.java. Thats exactly what my code with the Urls shoud do
![urlLoad-Method 1] there should be an image if i had 10 reputation
it gives out the numbers in the console with the given time from the slider.
Then i added my engine.load() part to the first "urlLoad"-Method
//updateMessage("Iteration " + i);
//updateProgress(i, 1000);
String Link = url.get(i);
engine.load(Link);
System.out.println("Url loaded = " + Link);
But then the method stops at the first Url and doesnt show anything:
![urlLoad-Method 1 with engine.load] there should be an image if i had 10 reputation
My assumption is, that the "urlLoad"-Method does not update the WebView Window in my GUI. I hope somebody can help me.
Thanks
Edit: After adding
task.setOnFailed((WorkerStateEvent t) -> {
throw new RuntimeException(task.getException());
});
I got the following exception:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
at application.FXMLController.lambda$2(FXMLController.java:111)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.concurrent.EventHelper.fireEvent(EventHelper.java:219)
at javafx.concurrent.Task.fireEvent(Task.java:1356)
at javafx.concurrent.Task.setState(Task.java:707)
at javafx.concurrent.Task$TaskCallable.lambda$call$502(Task.java:1453)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:279)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1243)
at javafx.scene.web.WebEngine.load(WebEngine.java:913)
at application.FXMLController$2.call(FXMLController.java:92)
at application.FXMLController$2.call(FXMLController.java:1)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1423)
at java.util.concurrent.FutureTask.run(Unknown Source)
... 1 more

you need to use
Platform.Runlater(()->{/*your task content here*/});
Javafx is pissy about what operations it allows you to run in which thread. Essentially, you have no business running code designated for ui control functionality on a non-ui thread... hence "thread 5" in your case.
Be careful, however, as you still need that thread.sleep routine in your background thread, as the javafx thread will sleep, and then proceed with the url.load() routine.
so...
javafxapplication thread (runs - handles its own operations)
thread 5 (runs whatever you want)
->
javafxapplication thread (runs but is idle from your POV)
thread 5 (invokes platform.runlater(/* engine.load("x") */))
->
javafxapplicationthread (executes engine.load())
thread 5 (etc etc etc)
good luck

Related

JavaFX FXML file not opening error chosen file should be valid FXML but it is working for other FXML files

I am working on image editor using JavaFX FXML ,scene builder 2.0 .I am getting this error continuously where my scene builder doesn't read FXML file when double clicking on it. I haven't used an other other libraries or anything and have tried opening particular FXML from scene builder directly as well.
I have tried using possible solutions on this question but non seems to work for me.
enter image description here
package imageeditor;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
import imageeditor.CommandCenter;
import javafx.scene.control.ColorPicker;
public class FXMLDocumentController implements Initializable {
// #FXML
// private Edit Images = new Edit();
// #FXML
// private ImageView ImageView,i ;
// #FXML private ImageView mImageView;
#FXML
private AnchorPane mAnchorPane;
#FXML
private ImageView mImageView;
#FXML
private Button btnUndo;
#FXML
private Button btnRedo;
#FXML
private Button exit;
#FXML
private Button reset;
#FXML
private Button uploadbtn,savebtn;
#FXML
private Label l1,l2,l3,l4,l5,l6,l7;
#FXML
private Slider bright;
#FXML
private Slider gauss;
#FXML
private Slider hue;
#FXML
private Slider saturation;
#FXML
private Slider contrast;
#FXML
private Button cropbtn ;
#FXML
private Button stickersbtn ;
#FXML
private Button textbtn ;
// #FXML
// private Button ;
#FXML
private ColorPicker framecolour ;
private ColorAdjust AdjustEffect = new ColorAdjust();
// CommandCenter CommandCenter= new CommandCenter();
#FXML
private void LoadImage(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = fileChooser.showOpenDialog(null);
try
{
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
mImageView.setImage(image);
Image currentImage = getSnapshot();
CommandCenter.getInstance().setImageAndView(currentImage);
CommandCenter.getInstance().setOriginalImage(currentImage);
// CommandCenter.getInstance().setImageView(mImageView);
// CommandCenter.getInstance().setOriginalImage(image);
} catch (IOException ex) {
}
}
#FXML
private void SaveImage(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Image");
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = fileChooser.showSaveDialog(null);
if (file != null) {
try {
BufferedImage bImage = SwingFXUtils.fromFXImage(mImageView.snapshot(null, null), null);
ImageIO.write(bImage,"png", file);
} catch (IOException ex) {
}
}
}
//#FXML void quit(ActionEvent event) {
// System.exit(0);
// }
#FXML void undo(ActionEvent event) {
undo();
}
#FXML void redo(ActionEvent event) {
redo();
}
// save image as snapshot
private Image getSnapshot() {
SnapshotParameters snapshotParameters = new SnapshotParameters();
snapshotParameters.setViewport(mImageView.getViewport());
// snapshotParameters.setViewport(new Rectangle2D(mImageView.getX(), mImageView.getY(), mImageView.getImage().getWidth(), mImageView.getImage().getHeight()));
return mAnchorPane.snapshot(snapshotParameters, null);
}
private void undo() {
if (CommandCenter.getInstance().hasUndoImage()) {
Image currentImage = getSnapshot();
CommandCenter.getInstance().addRedoImage(currentImage);
Image undoImage = CommandCenter.getInstance().getUndoImage();
resetEffectsSliders();
CommandCenter.getInstance().setImageAndView(undoImage);
mImageView.setImage(undoImage);
enableRedo();
if (!CommandCenter.getInstance().hasUndoImage()) {
disableUndo();
}
}
}
// redo action
private void redo() {
System.out.println("redo image added");
if (CommandCenter.getInstance().hasRedoImage()) {
Image currentImage = getSnapshot();
CommandCenter.getInstance().addUndoImage(currentImage);
Image redoImage = CommandCenter.getInstance().getRedoImage();
resetEffectsSliders();
CommandCenter.getInstance().setImageAndView(redoImage);
mImageView.setImage(redoImage);
enableUndo();
if (!CommandCenter.getInstance().hasRedoImage()) {
disableRedo();
}
}
}
// update the image and associated properties
private void updateImageAndProperties() {
CommandCenter.getInstance().storeLastImageAsUndo();
CommandCenter.getInstance().clearRedoImages(); // new "path" so clear redo images
disableRedo();
enableUndo();
Image currentImage = getSnapshot();
CommandCenter.getInstance().setImageAndView(currentImage);
resetEffectsSliders();
mImageView.setImage(currentImage);
}
// start over with original image
private void startOver() {
resetEffectsSliders();
Image originalImage = CommandCenter.getInstance().getOriginalImage();
CommandCenter.getInstance().setImageAndView(originalImage);
mImageView.setImage(originalImage);
CommandCenter.getInstance().clearRedoImages();
CommandCenter.getInstance().clearUndoImages();
disableUndo();
disableRedo();
}
private void resetEffectsSliders() {
bright.setValue(0);
contrast.setValue(0.0);
hue.setValue(0.0);
saturation.setValue(0.0);
}
// enable undo buttons
private void enableUndo() {
btnUndo.setDisable(false);
}
// disable undo buttons
private void disableUndo() {
btnUndo.setDisable(true);
}
// enable redo buttons
private void enableRedo() {
btnRedo.setDisable(false);
}
// disable redo buttons
private void disableRedo() {
btnRedo.setDisable(true);
}
// enable start over buttons
private void enableStartOver() {
reset.setDisable(false);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
CommandCenter.getInstance().setImageView(mImageView);
// Images.GaussSliderEvent(gauss);
// Images.BrightSliderEvent(bright);
// Images.SaturationSliderEvent(saturation);
// Images.HueSliderEvent(hue);
// Images.ContrastSliderEvent(contrast);
mImageView.setEffect(AdjustEffect);
// take a snapshot to set as initial image
Image initialImage = getSnapshot();
mImageView.setImage(initialImage);
CommandCenter.getInstance().setImageView(mImageView);
CommandCenter.getInstance().setOriginalImage(initialImage);
CommandCenter.getInstance().setImageAndView(initialImage);
// brightness slider
bright.valueProperty().addListener((observable, oldValue, newValue) -> {
AdjustEffect.setBrightness(newValue.doubleValue());
mImageView.setEffect(AdjustEffect);
updateImageAndProperties();
});
// hue slider
hue.valueProperty().addListener((observable, oldValue, newValue) -> {
AdjustEffect.setHue(newValue.doubleValue());
mImageView.setEffect(AdjustEffect);
updateImageAndProperties();
});
// saturation slider
saturation.valueProperty().addListener((observable, oldValue, newValue) -> {
AdjustEffect.setSaturation(newValue.doubleValue());
//Image.setEffect(AdjustEffect);
updateImageAndProperties();
});
// contrast slider
contrast.valueProperty().addListener((observable, oldValue, newValue) -> {
AdjustEffect.setContrast(newValue.doubleValue());
// Image.setEffect(AdjustEffect);
updateImageAndProperties();
});
// gauss slider
gauss.valueProperty().addListener((observable, oldValue, newValue) -> {
// gauss.setRadius(newValue.doubleValue()*100);
// Image.setEffect(gauss);
updateImageAndProperties();
});
}
}
Java FXML file is
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="650.0" prefWidth="1150.0" style="-fx-background-color: #FFFFF0;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="imageeditor.FXMLDocumentController">
<children>
<Button fx:id="uploadbtn" layoutX="797.0" layoutY="24.0" onAction="#LoadImage" opacity="0.75" style="-fx-background-color: #800000;" text="UPLOAD IMAGE" textFill="WHITE">
<font>
<Font name="Bell MT Bold" size="18.0" />
</font></Button>
<ImageView fx:id="ImageView" fitHeight="639.0" fitWidth="927.0" layoutX="201.0" layoutY="94.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#BG.jpg" />
</image></ImageView>
<Button fx:id="savebtn" layoutX="1007.0" layoutY="23.0" mnemonicParsing="false" onAction="#SaveImage" opacity="0.75" prefHeight="34.0" prefWidth="105.0" style="-fx-background-color: #800000;" text="SAVE" textFill="WHITE">
<font>
<Font name="Bell MT Bold" size="18.0" />
</font></Button>
<Button fx:id="resetbtn" layoutX="54.0" layoutY="576.0" text="RESET" />
<Button fx:id="undobtn" layoutX="25.0" layoutY="94.0" mnemonicParsing="false" style="-fx-background-color: #800000;" text="UNDO" textFill="WHITE" />
<Button fx:id="redobtn" layoutX="115.0" layoutY="94.0" mnemonicParsing="false" style="-fx-background-color: #800000;" textFill="WHITE"text="REDO" />
<Button fx:id="cropbtn" layoutX="63.0" layoutY="143.0" mnemonicParsing="false" text="CROP" />
<ColorPicker fx:id="framecolour" layoutX="52.0" layoutY="414.0" />
<Button fx:id="stickersbtn" layoutX="24.0" layoutY="516.0" mnemonicParsing="false" text="ADD STICKERS" />
<Button fx:id="textbtn" layoutX="44.0" layoutY="470.0" mnemonicParsing="false" text="ADD TEXT" />
<Slider fx:id="gauss" blockIncrement="0.1" layoutX="42.0" layoutY="315.0" max="1.0" min="0" />
<Slider fx:id="contrast" blockIncrement="0.01" layoutX="42.0" layoutY="237.0" max="1.0" min="-1.0" />
<Slider fx:id="hue" blockIncrement="0.01" layoutX="42.0" layoutY="199.0" max="1.0" min="-1.0" />
<Slider fx:id="saturation" blockIncrement="0.01" layoutX="42.0" layoutY="277.0" max="1.0" min="-1.0" />
<Slider fx:id="bright" blockIncrement="0.01" layoutX="38.0" layoutY="355.0" max="1.0" min="-1.0" />
<Slider fx:id="frame" blockIncrement="0.01" layoutX="42.0" layoutY="393.0" max="1.0" min="-1.0" />
<ImageView fitHeight="63.0" fitWidth="91.0" layoutX="31.0" layoutY="13.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#logo.png" />
</image>
</ImageView>
<Label fx:id="l1" layoutX="140.0" layoutY="18.0" prefHeight="51.0" prefWidth="451.0" text="IMAGE EDITOR AND ENHANCER" textFill="#830c0c">
<font>
<Font name="Artifakt Element Black Italic" size="29.0" />
</font>
</Label>
<Label fx:id="l2" layoutX="81.0" layoutY="182.0" text="hue" />
<Label fx:id="l3" layoutX="76.0" layoutY="220.0" text="contrast" />
<Label fx:id="l4" layoutX="68.0" layoutY="258.0" text="saturation" />
<Label fx:id="l5" layoutX="76.0" layoutY="298.0" text="gauss" />
<Label fx:id="l6" layoutX="74.0" layoutY="331.0" text="brightness" />
<Label fx:id="l7" layoutX="74.0" layoutY="376.0" text="frame" />
</children>
</AnchorPane>
SceneBuilder bring a stacktrace if you press show details button
Details :
java.io.IOException: org.xml.sax.SAXParseException; lineNumber: 28; columnNumber: 149; Element type "Button" must be followed by either attribute specifications, ">" or "/>".
at com.oracle.javafx.scenebuilder.kit.fxom.glue.GlueLoader.load(GlueLoader.java:93)
at com.oracle.javafx.scenebuilder.kit.fxom.glue.GlueLoader.load(GlueLoader.java:76)
at com.oracle.javafx.scenebuilder.kit.fxom.glue.GlueDocument.<init>(GlueDocument.java:54)
at com.oracle.javafx.scenebuilder.kit.fxom.FXOMDocument.<init>(FXOMDocument.java:84)
at com.oracle.javafx.scenebuilder.kit.fxom.FXOMDocument.<init>(FXOMDocument.java:108)
at com.oracle.javafx.scenebuilder.kit.editor.EditorController.updateFxomDocument(EditorController.java:2560)
at com.oracle.javafx.scenebuilder.kit.editor.EditorController.setFxmlTextAndLocation(EditorController.java:763)
at com.oracle.javafx.scenebuilder.app.DocumentWindowController.loadFromFile(DocumentWindowController.java:389)
at com.oracle.javafx.scenebuilder.app.SceneBuilderApp.performOpenFiles(SceneBuilderApp.java:668)
at com.oracle.javafx.scenebuilder.app.SceneBuilderApp$1.invalidated(SceneBuilderApp.java:520)
at javafx.base/com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(Unknown Source)
at javafx.base/com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at javafx.base/javafx.beans.property.ReadOnlyBooleanPropertyBase.fireValueChangedEvent(Unknown Source)
at javafx.base/javafx.beans.property.ReadOnlyBooleanWrapper.fireValueChangedEvent(Unknown Source)
at javafx.base/javafx.beans.property.BooleanPropertyBase.markInvalid(Unknown Source)
at javafx.base/javafx.beans.property.BooleanPropertyBase.set(Unknown Source)
at com.oracle.javafx.scenebuilder.kit.library.user.UserLibrary.lambda$updateFirstExplorationCompleted$7(UserLibrary.java:371)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(Unknown Source)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: org.xml.sax.SAXParseException; lineNumber: 28; columnNumber: 149; Element type "Button" must be followed by either attribute specifications, ">" or "/>".
at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.seekCloseOfStartTag(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.oracle.javafx.scenebuilder.kit.fxom.glue.GlueLoader.load(GlueLoader.java:91)
... 23 more
java.io.IOException: org.xml.sax.SAXParseException; lineNumber: 28; columnNumber: 149;
Line 28:
<Button fx:id="redobtn" layoutX="115.0" layoutY="94.0" mnemonicParsing="false" style="-fx-background-color: #800000;" textFill="WHITE"text="REDO" />
Error: there is no space in between textFill and text attributes , so Compiler can't read properly button tag
fix line 28 :
<Button fx:id="redobtn" layoutX="115.0" layoutY="94.0" mnemonicParsing="false" style="-fx-background-color: #800000;" textFill="WHITE" text="REDO" />
Now scenebuilder can open that file

javafx button positoning in scene

how can I set a button's position in the middle for all size of anchorpane in javafx scenebuilder.....
like this code...
the button should be in the middle even if i set the scene into the middle
i have tried so many times but couldent get it...
thanks in advance
if you dont understand try to run the code in IDE and then maximize it and again minimize it...
observe the position of the button
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.*;
import javafx.stage.WindowEvent;
import java.util.Optional;
public class Javafxpopupmessage extends Application {
private Stage mainStage;
#Override
public void start(Stage stage) throws Exception {
this.mainStage = stage;
stage.setOnCloseRequest(confirmCloseEventHandler);
Button closeButton = new Button("Close Application");
closeButton.setOnAction(event ->
stage.fireEvent(
new WindowEvent(
stage,
WindowEvent.WINDOW_CLOSE_REQUEST
)
)
);
StackPane layout = new StackPane(closeButton);
layout.setPadding(new Insets(100));
stage.setScene(new Scene(layout));
stage.show();
}
private EventHandler<WindowEvent> confirmCloseEventHandler = event -> {
Alert closeConfirmation = new Alert(
Alert.AlertType.CONFIRMATION,
"Are you sure you want to exit?"
);
Button exitButton = (Button)
closeConfirmation.getDialogPane().lookupButton(
ButtonType.OK
);
exitButton.setText("Exit");
closeConfirmation.setHeaderText("Confirm Exit");
closeConfirmation.initModality(Modality.APPLICATION_MODAL);
closeConfirmation.initOwner(mainStage);
// normally, you would just use the default alert positioning,
// but for this simple sample the main stage is small,
// so explicitly position the alert so that the main window can still be
seen.
closeConfirmation.setX(mainStage.getX());
closeConfirmation.setY(mainStage.getY() + mainStage.getHeight());
Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
if (!ButtonType.OK.equals(closeResponse.get())) {
event.consume();
}
};
public static void main(String[] args) {
launch(args);
}
}
This can not be done directly in AnchorPane because positions are fixed there. You must use a container that allows "floating positioning". For example HBox.
<AnchorPane xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
<children>
<HBox alignment="CENTER" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Button text="Exit" />
</children>
</HBox>
</children>
</AnchorPane>

How can I click a GridPane Cell and have it perform an action?

I'm new to JavaFX (Java for that matter) and I want to be able to click a GridPane and have it display my room attributes in a side-panel(or to console at this point). I've managed to setup a mouse event but I don't think it's the right tool for the job. When I click anywhere in the grid, it returns "null" and won't give me the cell coordinates(maybe there's better or more useful info to gather here?).
I'm using Scene Builder as well.
Controller Class
import Data.Area;
import Model.Grid;
import Model.TileSet;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Controller {
InputStream rinput = getClass().getResourceAsStream("/red.png");
Image red = new Image(rinput);
ImageView redimg = new ImageView(red);
InputStream binput = getClass().getResourceAsStream("/black.png");
Image black = new Image(binput);
InputStream pinput = getClass().getResourceAsStream("/pink.png");
Image pink = new Image(binput);
#FXML
public GridPane gridmane;
public void genSmall(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(40, 40));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
importGrid(gridmane, grid);
gridmane.getScene().getWindow().sizeToScene();
}
public void genMed(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(60, 60));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
gridmane.getScene().getWindow().sizeToScene();
gridmane.getScene().getWindow().setHeight(600);
gridmane.getScene().getWindow().setWidth(600);
importGrid(gridmane, grid);
}
public void genLarge(ActionEvent actionEvent) throws IOException {
Grid grid = new Grid(new Area(80, 80));
grid.getPathfinder().shufflePartitions();
grid.getPathfinder().fillPartitions();
grid.getPathfinder().generateHallways();
grid.getPathfinder().placeWalls();
gridmane.getScene().getWindow().sizeToScene();
gridmane.getScene().getWindow().setHeight(800);
gridmane.getScene().getWindow().setWidth(800);
importGrid(gridmane, grid);
}
private void importGrid(GridPane gridPane, Grid grid) {
gridPane.getChildren().clear(); // remove old children
for (int i = 0; i < grid.getSize().height; i++) {
for (int j = 0; j < grid.getSize().width; j++) {
if (grid.getContent()[j + (i * grid.getSize().width)] == TileSet.floorTile) {
changeSquare(gridPane, i, j, Color.WHITE, red);
}
else if (grid.getContent()[j + (i * grid.getSize().width)] == TileSet.wallTile) {
changeSquare(gridPane, i, j, Color.GRAY, black);
}
else {
changeSquare(gridPane, i, j, Color.BLACK, pink);
}
}
}
}
private void changeSquare(GridPane gridPane, int xCoordinate, int yCoordinate, Color color, Image image) {
Rectangle rect = new Rectangle();
ImageView fimage = new ImageView(image);
rect.setStroke(Color.BLACK);
rect.setFill(color);
rect.setWidth(10);
rect.setHeight(10);
gridPane.add(fimage, xCoordinate, yCoordinate);
}
public void clickGrid(javafx.scene.input.MouseEvent event) {
Node source = (Node)event.getSource() ;
Integer colIndex = gridmane.getColumnIndex(source);
Integer rowIndex = gridmane.getRowIndex(source);
System.out.println("Mouse clicked cell: " + colIndex + "And: " + rowIndex);
}
}
Main Class
public class Main extends Application {
Stage stage = new Stage();
int val = 40;
#Override
public void start(Stage primaryStage) throws Exception {
this.stage = primaryStage;
setVal(val);
}
public static void main(String[] args) {
launch(args);
}
public void setVal(int i) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("/view.fxml"));
stage.setTitle("Dungeon Generator");
stage.setScene(new Scene(root, 450, 450));
//primaryStage.setResizable(false);
stage.sizeToScene();
stage.show();
}
}
FXML File
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.image.Image?>
<VBox maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="258.0" prefWidth="332.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<children>
<MenuBar>
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
<HBox alignment="CENTER" prefHeight="100.0" prefWidth="200.0">
<children>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genSmall" prefHeight="27.0" prefWidth="64.0" text="Small" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genMed" text="Medium" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
<Button alignment="CENTER" mnemonicParsing="false" onAction="#genLarge" prefHeight="27.0" prefWidth="66.0" text="Large" HBox.hgrow="ALWAYS">
<HBox.margin>
<Insets left="20.0" />
</HBox.margin>
</Button>
</children>
</HBox>
<StackPane>
<children>
<GridPane fx:id="gridmane" maxHeight="-Infinity" maxWidth="-Infinity" onMouseClicked="#clickGrid" VBox.vgrow="NEVER" />
</children>
</StackPane>
</children>
</VBox>
Since you register the event handler at the GridPane, the source of the event is the GridPane itself. You did not set the row/column index for the GridPane and it wouldn't contain any useful information.
In this case you need to get the node that was actually clicked from the MouseEvent:
public void clickGrid(javafx.scene.input.MouseEvent event) {
Node clickedNode = event.getPickResult().getIntersectedNode();
if (clickedNode != gridmane) {
// click on descendant node
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}
}
In this case the code works like this since the children of your GridPane don't have children of their own that could be the intersected node.
If you want to add children that could have children of their own you need to go up through the node hierarchy until you find a child of the GridPane:
if (clickedNode != gridmane) {
// click on descendant node
Node parent = clickedNode.getParent();
while (parent != gridmane) {
clickedNode = parent;
parent = clickedNode.getParent();
}
Integer colIndex = GridPane.getColumnIndex(clickedNode);
Integer rowIndex = GridPane.getRowIndex(clickedNode);
System.out.println("Mouse clicked cell: " + colIndex + " And: " + rowIndex);
}

Javafx: How can I code the calculation to get results when I click the button?

package javafx_tipcalc;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.text.NumberFormat;
public class JavaFX_TipCalc extends Application {
// declare interface controls
// declare labels
Label titleLabel, checkAmtLabel, tipPercentLabel, splitLabel;
Label tipAmtLabel, totalLabel, amtPerPersonLabel;
// declare text fields
TextField checkAmtText, tipAmtText, totalText, amtPerPersonText;
// declare a slider
Slider tipPercentSlider;
// declare a choice box
ChoiceBox splitChoiceBox;
// declare a button
Button calcTipButton;
// declare currency and percent formatter
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat persent = NumberFormat.getCurrencyInstance();
// declare a grid pane (8 rows and 2 columns)
GridPane grid;
#Override
public void start(Stage primaryStage) {
// instantiate labels and their properties
titleLabel = new Label("Tip Calculator");
titleLabel.setMaxWidth(Double.MAX_VALUE);
titleLabel.setAlignment(Pos.CENTER);
checkAmtLabel = new Label("Check Amount");
checkAmtLabel.setMaxWidth(Double.MAX_VALUE);
checkAmtLabel.setAlignment(Pos.CENTER_RIGHT);
tipPercentLabel = new Label("Tip Percent: 15%");
tipPercentLabel.setMaxWidth(Double.MAX_VALUE);
tipPercentLabel.setAlignment(Pos.CENTER_RIGHT);
splitLabel = new Label("Split");
splitLabel.setMaxWidth(Double.MAX_VALUE);
splitLabel.setAlignment(Pos.CENTER_RIGHT);
tipAmtLabel = new Label("Tip Amount");
tipAmtLabel.setMaxWidth(Double.MAX_VALUE);
tipAmtLabel.setAlignment(Pos.CENTER_RIGHT);
totalLabel = new Label("Total");
totalLabel.setMaxWidth(Double.MAX_VALUE);
totalLabel.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonLabel = new Label("Amount per Person");
amtPerPersonLabel.setMaxWidth(Double.MAX_VALUE);
amtPerPersonLabel.setAlignment(Pos.CENTER_RIGHT);
// instantiate text fileds and their properties
double textFieldWidth = 100;
checkAmtText = new TextField();
checkAmtText.setOnMouseClicked(e -> ResetFields());
checkAmtText.setPrefWidth(textFieldWidth);
checkAmtText.setAlignment(Pos.CENTER_RIGHT);
tipAmtText = new TextField();
tipAmtText.setFocusTraversable(false);
tipAmtText.setPrefWidth(textFieldWidth);
tipAmtText.setAlignment(Pos.CENTER_RIGHT);
tipAmtText.setEditable(false);
totalText = new TextField();
totalText.setFocusTraversable(false);
totalText.setPrefWidth(textFieldWidth);
totalText.setAlignment(Pos.CENTER_RIGHT);
totalText.setEditable(false);
amtPerPersonText = new TextField();
amtPerPersonText.setFocusTraversable(false);
amtPerPersonText.setPrefWidth(textFieldWidth);
amtPerPersonText.setAlignment(Pos.CENTER_RIGHT);
amtPerPersonText.setEditable(false);
// instantiate a slider and its properties
tipPercentSlider = new Slider();
tipPercentSlider.setPrefWidth(10);
tipPercentSlider = new javafx.scene.control.Slider();
tipPercentSlider.setPrefWidth(150);
tipPercentSlider.setMin(0);
tipPercentSlider.setMax(25);
tipPercentSlider.setMajorTickUnit(5);
tipPercentSlider.setMinorTickCount(1);
tipPercentSlider.setBlockIncrement(1);
tipPercentSlider.setShowTickLabels(true);
tipPercentSlider.setShowTickMarks(true);
tipPercentSlider.setSnapToTicks(true);
tipPercentSlider.setValue(15);
tipPercentSlider.setOrientation(Orientation.HORIZONTAL);
tipPercentSlider.valueProperty().addListener(
(observable, oldvalue, newvalue) ->
{
tipPercentLabel.setText(String.format("Tip Percent:
%2d%s",newvalue.intValue(),"%"));
} );
// instantiate a choice box and its properties
splitChoiceBox = new ChoiceBox();
splitChoiceBox.getItems().addAll("1 Way", "2 Ways", "3 Ways", "4
Ways", "5 Ways");
splitChoiceBox.setValue("1 Way");
splitChoiceBox.setPrefWidth(150);
// instantiate a button and its properties
calcTipButton = new Button("Calculate Tip");
calcTipButton.setMaxWidth(Double.MAX_VALUE);
calcTipButton.setOnAction(e -> CalcButtonClick()) ;
// instantiate a grid pane and its properties
grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(10));
grid.add(titleLabel, 0, 0, 2, 1);
grid.addRow(1, checkAmtLabel, checkAmtText);
grid.addRow(2, tipPercentLabel, tipPercentSlider);
grid.addRow(3, splitLabel, splitChoiceBox);
grid.add(calcTipButton, 0, 4, 2, 1);
grid.addRow(5, tipAmtLabel, tipAmtText);
grid.addRow(6, totalLabel, totalText);
grid.addRow(7, amtPerPersonLabel, amtPerPersonText);
// instantiate the grid pane and put items in in grid
Scene scene = new Scene(grid);
scene.getRoot().setStyle("-fx-font: 20 'Comic Sans MS'");
primaryStage.setTitle("Tip Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private void CalcButtonClick() {
/*
Get the check amount from checkAmtText
Get the tip percent from the slider
Get the split the choice box
Tip amount = check amount * tip percent
Total amount = check amount + tip amount
Amount per person = total amount / split
Print the tip amount in tipAmtText
Print the total amount in total Text
Print the split amtPerPerson Text
*/
double tipAmnt, checkAmnt, tipPercent,
totalAmnt, AmntPerPerson;
tipAmnt = Double.parseDouble(tipAmtText.getText());
AmntPerPerson =
Double.parseDouble(amtPerPersonText.getText());
checkAmnt = Double.parseDouble(checkAmtText.getText());
totalAmnt = Double.parseDouble(totalText.getText());
tipPercent = Double.parseDouble(tipPercentLabel.getText());
tipAmnt = checkAmnt * tipPercent;
totalAmnt = checkAmnt + tipAmnt;
tipAmtText.setText(currency.format(tipAmnt));
totalText.setText(currency.format(totalAmnt));
}
private void ResetFields() {
/*
Clear the check amount
Clear the tip amount
Clear the total amount
Clear the amount per person
Set the tip percent slider to 15%
Set the split choice box to “1 Way”
*/
}
}
You should use eventListener or FXML. Second, I think, would be easier. Need example?
UPDATE: (I added an example)
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation((getClass().getResource("Sample.fxml")));
Parent panel = fxmlLoader.load();
Scene scene = new Scene(panel, 300, 150);
primaryStage.setTitle("Sum of two numbers");
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Sample.fxml
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="150.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController">
<children>
<AnchorPane prefHeight="55.0" prefWidth="300.0">
<children>
<HBox prefHeight="25.0" prefWidth="200.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0">
<children>
<Label text="x">
<HBox.margin>
<Insets left="31.0" />
</HBox.margin>
</Label>
<Label text="y">
<HBox.margin>
<Insets left="62.0" />
</HBox.margin>
</Label>
<Label text="z">
<HBox.margin>
<Insets left="62.0" />
</HBox.margin>
</Label>
</children>
</HBox>
<HBox prefHeight="100.0" prefWidth="200.0" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
<children>
<TextField fx:id="xTextField" />
<TextField fx:id="yTextField" />
<TextField fx:id="zTextField" />
</children>
</HBox>
</children>
</AnchorPane>
<AnchorPane prefHeight="200.0" prefWidth="200.0">
<HBox AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0">
<children>
<Button mnemonicParsing="false" onAction="#sumIt" text="Sum it!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
</children>
<children>
<Button mnemonicParsing="false" onAction="#clearAll" text="Clear all!" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="20.0" />
</children>
</HBox>
</AnchorPane>
</children>
</VBox>
SampleController.java
package application;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class SampleController {
#FXML
TextField xTextField, yTextField, zTextField;
public void sumIt() {
int sum;
sum = Integer.parseInt(xTextField.getText()) + Integer.parseInt(yTextField.getText());
zTextField.setText(Integer.toString(sum));
}
public void clearAll() {
xTextField.setText("");
yTextField.setText("");
zTextField.setText("");
}
}

ScrollPane containing ImageView does not update its scrollbars after calling setImage()

I am experimenting JavaFX with a simple image viewer. I want it to display an image and, if it does not fit in the window, display scrollbars. The image to dislay is loaded with the FileChooser and set to the ImageView using imageView.setImage(image).
The problem is that the scrollbars of the containing ScrollPane do not update after calling imageView.setImage(image). Instead, I need to perform an action that changes the scene (e.g. resize the window). It behaves the same when an image is displayed and another is loaded, i.e. the sizes of the scrollbars reflect the size of the previous image.
The bug is reproducible using the following cut-down version of the code:
(Java)
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class ImageViewerBug extends Application
{
#FXML private ImageView imageView;
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("ImageViewerBug.fxml"));
fxmlLoader.setController(this);
try {
BorderPane borderPane = (BorderPane) fxmlLoader.load();
Scene scene = new Scene(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
}
catch( IOException e ) {
throw new RuntimeException(e);
}
}
public void loadClicked() {
FileChooser fileChooser = new FileChooser();
File f = fileChooser.showOpenDialog(null);
if( f != null ) {
try( InputStream is = new FileInputStream(f) ) {
Image image = new Image(is);
imageView.setImage(image);
}
catch( IOException e ) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
launch(args);
}
}
(FXML)
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.Group?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane id="BorderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
<center>
<ScrollPane prefHeight="200.0" prefWidth="200.0">
<content>
<Group>
<ImageView fx:id="imageView" pickOnBounds="true" preserveRatio="true" />
</Group>
</content>
</ScrollPane>
</center>
<top>
<ToolBar>
<items>
<Button mnemonicParsing="false" onAction="#loadClicked" text="Load" />
</items>
</ToolBar>
</top>
</BorderPane>
I can confirm this bug. A quick and dirty workaround that fixed it for me:
public void loadClicked() {
FileChooser fileChooser = new FileChooser();
File f = fileChooser.showOpenDialog(null);
if( f != null ) {
try( InputStream is = new FileInputStream(f) ) {
Image image = new Image(is);
imageView.setImage(image);
imageView.snapshot(new SnapshotParameters(), new WritableImage(1, 1));
double rnd = new Random().nextInt(10);
imageView.setX(rnd/1000);
imageView.setY(rnd/1000);
}
catch( IOException e ) {
e.printStackTrace();
}
}
}
The snapshot() Method sometimes works like a charm whenever some UI-element isn't updated or displayed correctly. But don't ask me why that works, maybe it has something to do with the rendering process, because snapshots forces JavaFX to render the scene graph or the target elements. The random stuff is needed to create the right scrollbar sizes when adding a new image after one already part of the ImageView.
Maybe this has something to do with the strange behaviour i found some weeks earlier. The workaround also solved my problems back then.
(Really late)EDIT
The problem is caused by the Group which wraps the ImageView. If you use a node that inherits from Pane the behaviour of the ScrollPane should be as expected even without the workaround. A Group can still be used as the direct child of the ScrollPane as long as a Pane wraps the ImageView.
Example:
<ScrollPane prefHeight="200.0" prefWidth="200.0">
<content>
<Group id="Group">
<children>
<HBox id="HBox" alignment="CENTER" layoutX="0.0" layoutY="0.0" spacing="5.0">
<children>
<ImageView fx:id="imageView" pickOnBounds="true" preserveRatio="true" />
</children>
</HBox>
</children>
</Group>
</content>
</ScrollPane>
I have had the same problem with image...Instead of
Image image = new Image(is);
You should write:
Image image = new Image("file:" + ABSOLUTE_PATH_TO_FILE);
Image will refresh automatically, you don't have to do anything. For me, it works
use the command:
Scrollbar scrollbar
// ...
// Some activities with children that extends canvas, so scrollbar is needed.
// ...
scrollbar.layout();
this will update your scrollbar.
No Workaround needed.

Resources