import java.io.File;
import java.util.Scanner;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class ShakespeareUI extends Application {
public String Quotes(String fileName) throws Exception{
File file = new File (fileName);
String line ="";
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
line+= sc.nextLine();
}
return line;
}
#Override // Override the start method in the Application class
public void start(Stage primaryStage)throws Exception {
BorderPane pane = new BorderPane();
// Top of Pane with Text
Pane paneForText = new Pane();
paneForText.setPadding(new Insets(0,0,5,0));
Text shText = new Text(25, 50,"Shakespeare Quotes");
shText.setFont(Font.font("Arial", 28));
paneForText.getChildren().add(shText);
pane.setTop(paneForText);
// Center of Border Pane with TextArea
TextArea taQuote = new TextArea();
taQuote.setPrefColumnCount(30);
taQuote.setPrefRowCount(5);
pane.setCenter(taQuote);
// Bottom of Pane with Buttons
HBox paneForButtons = new HBox(20);
Button btLear = new Button("King Lear");
Button btMacBeth = new Button("MacBeth");
Button btHamlet = new Button("Hamlet");
Button btRichard = new Button("Richard III");
Button btOthello = new Button("Othello");
pane.setBottom(paneForButtons);
paneForButtons.getChildren().addAll(btLear, btMacBeth, btHamlet, btRichard, btOthello );
paneForButtons.setAlignment(Pos.CENTER);
paneForButtons.setStyle("-fx-border-color: green");
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 455, 150);
primaryStage.setTitle("Deep Patel"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
////// Your code here that handles events when buttons are clicked
btLear.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
shText.setText(btLear.getText());
taQuote.setText(Quotes("lear.txt"));
}
});
btMacBeth.setOnAction(new EventHandler<ActionEvent>(){
#Override public void handle(ActionEvent e){
shText.setText(btMacBeth.getText());
}
});
btHamlet.setOnAction(new EventHandler<ActionEvent>(){
#Override public void handle(ActionEvent e){
shText.setText(btHamlet.getText());
}
});
btRichard.setOnAction(new EventHandler<ActionEvent>(){
#Override public void handle(ActionEvent e){
shText.setText(btRichard.getText());
}
});
btOthello.setOnAction(new EventHandler<ActionEvent>(){
#Override public void handle(ActionEvent e){
shText.setText(btOthello.getText());
}
});
}
/////////////////////////////////////////////////////
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
Hi, I am trying to run this code but there is error about exception. I have no idea what to do. Thanks in advance for any help. I tried to put exception in the override method, in the general method and then I just made new method and put exception there but still the same here
The error that I am getting is this:
ShakespeareUI.java:79: error: unreported Exception; must be caught or
declared to be thrown
The EventHandler method does not allow you to add a throws clause for non-runtime exceptions. Therefore you need to use try-catch to handle those exceptions even if you just handle them by rethrowing the exception as RuntimeException (which is not a good way to handle failed execution of code in most cases):
btLear.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
shText.setText(btLear.getText());
try {
taQuote.setText(Quotes("lear.txt"));
} catch (Exception ex) {
// TODO: handle exception in a differnt way???
throw new RuntimeException(ex);
}
}
});
Note that you should close any classes accessing files as soon as you're done with the reader/writer. (Scanner in this case):
public String Quotes(String fileName) throws Exception{
File file = new File (fileName);
StringBuilder builder = new StringBuilder(); // builder more efficient for concatenating multiple strings
try(Scanner sc = new Scanner(file)) { // try-with-resources automatically calls close on scanner
while(sc.hasNextLine()) {
builder.append(sc.nextLine());
}
return builder.toString();
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
Here I have written the following code. I can't run the program, and the error mentioned below keeps appearing. I tried many probable solutions but in vain.
import java.beans.EventHandler;
import java.io.File;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileChooser_1 extends Application {
// launch the application
public void start(Stage stage) {
try {
// title
stage.setTitle("Filechooser");
//File chooser create
FileChooser file_chooser = new FileChooser();
// define Label
Label lab = new Label("select file");
// Button new
Button b = new Button("open dialog");
// create Event Handler
EventHandler<ActionEvent> eve
= new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
// get file
File file = file_chooser.showOpenDialog(stage);
if (file != null) {
lab.setText(file.getAbsolutePath()
+ " selected");
}
}
};
b.setOnAction(event);
// create Button
Button b1 = new Button("save");
// Event Handler
EventHandler<ActionEvent> eve1
= new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
// get file
File file = file_chooser.showSaveDialog(stage);
if (file != null) {
lab.setText(file.getAbsolutePath()
+ " selected");
}
}
};
b1.setOnAction(eve1);
// VBox
VBox vbox = new VBox(30, label, button, button1);
// set Alignment
vbox.setAlignment(Pos.CENTER);
// create scene
Scene scene = new Scene(vbox, 800, 500);
// scene
stage.setScene(scene);
stage.show();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// Main Method
public static void main(String args[]) {
launch(args);
}
}
I am getting the following error:
Error: Unable to initialize main class FileChooser_1
Caused by: java.lang.NoClassDefFoundError: Stage
It will be really nice if you can help me with this.
With some attention to detail, your code works. In particular, especially when just starting out,
Use Java naming conventions.
Use meaningful names; for example, instead of Button b, try Button openButton.
When using detailed comments, keep them up to date; note how meaningful names make some comments superfluous.
Use constants for consistency.
As #jewelsea notes, your program imports java.beans.EventHandler; it should import javafx.event.EventHandler.
As #jewelsea notes, "Only import classes you use."
Let the layout do the work.
I can't explain the error in your question; I see errors related to the incorrect import for EventHandler. If you're using an IDE, it may be reporting errors from a different compilation unit. When in doubt, do a clean build, move the code to a new file, or move to a different development environment, e.g. the command line. As a concrete example, this simple VersionCheck illustrates both a minimal ant script, invoked as ant run, and a simple shell script, invoked as .run.sh:
#!/bin/sh
JFX="--module-path /Users/Shared/javafx-sdk-17.0.1/lib --add-modules ALL-MODULE-PATH"
javac $JFX *.java && java $JFX VersionCheck
import javafx.event.EventHandler;
import java.io.File;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileChooser1 extends Application {
private static final int PADDING = 32;
#Override
public void start(Stage stage) {
// title
stage.setTitle("FileChooser");
//File chooser create
FileChooser fileChooser = new FileChooser();
// define Label
Label label = new Label("Select a file to open or save:");
// open Button
Button openButton = new Button("Open");
// open Event Handler
EventHandler<ActionEvent> openHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// get file name
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
label.setText(file.getName() + " selected");
}
}
};
openButton.setOnAction(openHandler);
// create save button
Button saveButton = new Button("Save");
// save Event Handler
EventHandler<ActionEvent> saveHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
// save file
File file = fileChooser.showSaveDialog(stage);
if (file != null) {
label.setText(file.getName() + " selected");
}
}
};
saveButton.setOnAction(saveHandler);
// VBox
VBox vBox = new VBox(PADDING, label, openButton, saveButton);
// set Alignment
vBox.setAlignment(Pos.CENTER);
vBox.setPadding(new Insets(PADDING));
// create scene
Scene scene = new Scene(vBox);
// scene
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
I'm new to JavaFX. I try to program a simple GUI but I face those problem whom might be related.
I set files with a File Chooser and want to do pretty basic operations:
save the last folder used
write the name of the selected file in the VBox
Here's my code (which compiles):
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
public static Stage primaryStageS;
public static Scene mainScene;
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene((new Test(primaryStage).getScene()));
primaryStageS = primaryStage;
primaryStage.setTitle("Parcel Manager Main Page");
primaryStage.initStyle(StageStyle.DECORATED);
VBox main = new VBox(new Label("Test program"));
mainScene = new Scene(main, 800, 600);
primaryStage.setScene((new Test(primaryStage)).getScene());
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public class Object1 {
String name;
public Object1(File f) throws IOException {
name = f.getName();
}
public String getName() {
return name;
}
}
public class Test {
Object1 collec;
String collecName;
File lastFolder;
Pane rootGroup;
public Test(Stage stage) {
setButtons(stage);
}
public void setButtons(Stage stageGoal) {
VBox vbox = new VBox();
Button b = getButton(stageGoal);
vbox.getChildren().addAll(b, new Label(getCollecName() == null ? "no name" : collecName));
final GridPane inputGridPane = new GridPane();
GridPane.setConstraints(vbox, 0, 0);
inputGridPane.getChildren().addAll(vbox);
rootGroup = new VBox(12);
rootGroup.getChildren().addAll(inputGridPane);
rootGroup.setPadding(new Insets(12, 12, 12, 12));
}
public Button getButton(Stage stage) {
FileChooser fileChooserParcel = new FileChooser();
fileChooserParcel.setInitialDirectory(getLastFolder());
Button button = new Button("Select a File");
button.setOnAction(e -> {
File f = fileChooserParcel.showOpenDialog(stage);
if (f != null) {
try {
collec = new Object1(f);
} catch (IOException e1) {
e1.printStackTrace();
}
setLastFolder(f.getParentFile());
setCollecName(collec);
setButtons(stage); // tried to reload every buttons - doesn't work
stage.setWidth(stage.getWidth() + 0.0001); // found this dirty hack but doesn't work
}
});
return button;
}
public void setCollecName(Object1 o1) {
collecName = o1.getName();
}
public String getCollecName() {
return collecName;
}
public File getLastFolder() {
return lastFolder;
}
public void setLastFolder(File folder) {
System.out.println("set last folder: " + folder);
lastFolder = folder;
}
private Scene getScene() {
return new Scene(rootGroup, 800, 600);
}
}
}
I cannot refresh the Nodes, either to set a current Initial Directory or display the collecName on the VBox. I tried to regenerate them with reloading of objects or resizing the window, but nothing works. When I print the variables on console, I see that they changes. But haven't found any refresh method for any of my objects.
I bet it's a design program issue, but I have been moving things around for the last week and doesn't know how to fix this.
Thanks !
You are only setting the initial directory once. I guess you want to set it every time you click the button. So move that line of code to inside the handler.
Compare the below getButton() method with yours.
public Button getButton(Stage stage) {
FileChooser fileChooserParcel = new FileChooser();
Button button = new Button("Select a File");
button.setOnAction(e -> {
fileChooserParcel.setInitialDirectory(getLastFolder()); // CHANGE HERE.
File f = fileChooserParcel.showOpenDialog(stage);
if (f != null) {
try {
collec = new Object1(f);
} catch (IOException e1) {
e1.printStackTrace();
}
setLastFolder(f.getParentFile());
setCollecName(collec);
setButtons(stage); // tried to reload every buttons - doesn't work
stage.setWidth(stage.getWidth() + 0.0001); // found this dirty hack but doesn't work
}
});
return button;
}
I am working on an App that simulates an online shop for my Data Structures course, I am currently using JavaFX in the Eclipse IDE and Scene Builder for the GUI design, however I am trying to use a Double LinkedList to store the Accounts in the Sign In UI window, but for some reason every time that I try to insert a new Account object (in the Action Event method) into my List it doesn't inserts it, at least if I try to print it´s toString gives me a Null pointer Exception, but if the insert and the println is in the start method works. Last year a did an MP3 player using JavaFX but in Netbeans and I didn't use Scene Builder and the List did work, some one has any idea why is this happening?
package com.javafx.quvbi.controller;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.input.MouseEvent;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class interfazController extends Application {
#FXML
private Button pausa, CreateAccBttn, LoginBttn;
#FXML
private TextField NameTF, AccountTF, PasswordTF, CardTF;
//Data
ListaDobleEnlazada<Account> accList;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//NameTF = new TextField();
//AccountTF = new TextField();
//PasswordTF= new TextField();
//CardTF = new TextField();
accList = new ListaDobleEnlazada<Account>();
//accList.insertarInicio(new Account("Diego","Qubi","22f24rf2",123321));
Parent root = FXMLLoader.load(getClass().getResource("/view/OptionUI.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(accList.toString());
}
public ListaDobleEnlazada<Account> getAccounts() {
return accList;
}
#FXML
public void controlMusica(ActionEvent event) {
System.out.println("musica");
System.out.println(getAccounts().getInicio().toString());
}
public void CreateAccClick(MouseEvent event) throws IOException {
if(!NameTF.getText().isEmpty() && !AccountTF.getText().isEmpty() && !PasswordTF.getText().isEmpty() && !CardTF.getText().isEmpty()) {
accList.insertarInicio(new Account(NameTF.getText(), AccountTF.getText(), PasswordTF.getText(), Integer.parseInt(CardTF.getText())));
}
}
#SuppressWarnings("restriction")
public void createAccount(ActionEvent event) throws IOException {
if(!NameTF.getText().isEmpty() && !AccountTF.getText().isEmpty() && !PasswordTF.getText().isEmpty() && !CardTF.getText().isEmpty()) {
Parent loginUI = FXMLLoader.load(getClass().getResource("/view/GUI2.fxml"));
Scene logInScene = new Scene(loginUI);
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(logInScene);
window.show();
System.out.println(NameTF.getText());
System.out.println(AccountTF.getText());
System.out.println(PasswordTF.getText());
System.out.println(CardTF.getText());
//this.accList.insertarInicio(new Account(NameTF.getText(), AccountTF.getText(), PasswordTF.getText(), Integer.parseInt(CardTF.getText())));
}
}
public void loginAccount(ActionEvent event) throws IOException {
Parent loginUI = FXMLLoader.load(getClass().getResource("/view/GUI2.fxml"));
Scene logInScene = new Scene(loginUI);
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(logInScene);
window.show();
}
}
I want to develop an application that uses controlsfx Notifications to show some notifications in system tray mode. In normal mode my application works well and notification can be shown successfully.but when I hide stage in system tray , NullPointerException occurs. I don't know how i can fix this problem.
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class TryIconNotification extends Application {
private boolean firstTime;
private TrayIcon trayIcon;
#Override
public void start(Stage stage) throws Exception {
firstTime = true;
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
createTrayIcon(stage);
firstTime = true;
Platform.setImplicitExit(false);
stage.setScene(scene);
stage.show();
}
public void createTrayIcon(final Stage stage) {
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
java.awt.Image image = null;
image = Toolkit.getDefaultToolkit().getImage("icons\\iconify.png");
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
hide(stage);
}
});
// create a action listener to listen for default action executed on the tray icon
final ActionListener closeListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
stage.hide();
}
};
ActionListener showListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Open app");
showItem.addActionListener(showListener);
popup.add(showItem);
MenuItem closeItem = new MenuItem("Exit");
closeItem.addActionListener(closeListener);
popup.add(closeItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Systray", popup);
// set the TrayIcon properties
trayIcon.addActionListener(showListener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
}
}
public void showProgramIsMinimizedMsg() {
//only in first time show the message
if (firstTime) {
trayIcon.displayMessage("System Tray",
"Iconified",
TrayIcon.MessageType.INFO);
firstTime = false;
}
}
private void hide(final Stage stage) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (SystemTray.isSupported()) {
stage.hide();
showProgramIsMinimizedMsg();
} else {
System.exit(0);
System.out.println("Not Support Sys Tray");
}
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And this is my controller Class:
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import org.controlsfx.control.Notifications;
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
Stage stage = (Stage) label.getScene().getWindow();
stage.hide();
}
public void createNotification() {
Notifications.create()
.text("This is a Notification")
.title("Notifications")
.showInformation();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Platform.runLater(()->createNotification());
}
}, 5000, 10000);
}
}
I realize that this exception occurs when the stage go to hide mode and the notification component cannot find stage when notification needs to show in stage. After searching in internet I find two solution for this problem.
Solution 1:
Open the stage and show notification.
In this way we should check that if the stage was hidden, open it , and show notification.
To do this we must add this condition in CreateNotification Method:
Stage stage = (Stage) button.getScene().getWindow();
if (!stage.isShowing()){
stage.show();
}
Solution 2:
In this solution we create a dummy stage and set its opacity to zero and after that, hide the main stage. I find this solution at this link and put the code in
here:
public void createDummyStage() {
Stage dummyPopup = new Stage();
dummyPopup.initModality(Modality.NONE);
// set as utility so no iconification occurs
dummyPopup.initStyle(StageStyle.UTILITY);
// set opacity so the window cannot be seen
dummyPopup.setOpacity(0d);
// not necessary, but this will move the dummy stage off the screen
final Screen screen = Screen.getPrimary();
final Rectangle2D bounds = screen.getVisualBounds();
dummyPopup.setX(bounds.getMaxX());
dummyPopup.setY(bounds.getMaxY());
// create/add a transparent scene
final Group root = new Group();
dummyPopup.setScene(new Scene(root, 1d, 1d, Color.TRANSPARENT));
// show the dummy stage
dummyPopup.show();
}
As I mention bellow, We should call this method before hiding the main stage:
#FXML
public void handleSysTryAction(ActionEvent event) {
Stage stage = (Stage) button.getScene().getWindow();
createDummyStage();
stage.hide();
}
I implement this two solution and every things works well. If you have a better solution for this problem please put here
You can download the complete Netbeans project from my Dropbox
I could not figure out why hamid's first solution was not working for me, until I debugged the Notifications creation. I found out, that beside the need of the Window to be isShowing it has to be isFocused too!
My solution is to call something like this method before Notifications.show():
private void focusStage() {
final Stage stage = (Stage) button.getScene().getWindow();
if (!stage.isShowing()) {
stage.show();
}
if (!stage.isFocused()) {
stage.requestFocus();
}
}
Currently I have a TextField which is my address bar and a WebView which is my page. When I click ented the TextField doesn't seem to do anything. It's meant to run the loadPage method and set to page to load whatever the user entered into the address bar. Any help would be appreciated.
package javafx_webview;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class Main extends Application {
WebEngine myWebEngine;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
primaryStage.setTitle("Platinum v1");
TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
loadPage(event.toString());
}
});
WebView myBrowser = new WebView();
myWebEngine = myBrowser.getEngine();
StackPane root = new StackPane();
root.getChildren().add(myBrowser);
root.getChildren().add(addressBar);
primaryStage.setScene(new Scene(root, 640, 480));
primaryStage.show();
}
private void loadPage(String url) {
try {
myWebEngine.load(url);
} catch (Exception e) {
System.out.println("The URL you requested could not be found.");
}
}
}
Get the url to load from the text of the address bar, not the toString of the action event on the address bar.
final TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
myWebEngine.load(addressBar.getText());
}
});
Also the load is asynchronous, so your exception handler won't work. You need to monitor's the webengine loadworker's exception property to get exceptions from the engine. Also note that a url not found is not necessarily an exception which would be reported, instead a web server will usually return a page for a http 404 error.
Here is a working sample:
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class Main extends Application {
private WebEngine myWebEngine;
public void start(Stage stage) {
stage.setTitle("Platinum v1");
final TextField addressBar = new TextField();
addressBar.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
myWebEngine.load(addressBar.getText());
}
});
WebView myBrowser = new WebView();
myWebEngine = myBrowser.getEngine();
myWebEngine.getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {
#Override public void changed(ObservableValue<? extends Throwable> observableValue, Throwable oldException, Throwable exception) {
System.out.println("WebView encountered an exception loading a page: " + exception);
}
});
VBox root = new VBox();
root.getChildren().setAll(
addressBar,
myBrowser
);
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) { launch(args); }
}