ProgressBar and mouse clicked event - java

I have a Label and a ProgressBar in a GridPane.
I've registered an onMouseClicked-event handler on the GridPane.
If I click on the Label the handler gets triggered.
If I click on the ProgressBar the handler doesn't get triggered.
Why? How can I fix it?
package test;
import javafx.application.Application;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.stage.Stage;
public class ProgressBarTestApplication extends Application {
#Override
public void start(Stage primaryStage) {
GridPane gridPane = new GridPane();
ColumnConstraints columnConstraints0 = new ColumnConstraints();
columnConstraints0.setHgrow(Priority.SOMETIMES);
ColumnConstraints columnConstraints1 = new ColumnConstraints();
columnConstraints1.setHgrow(Priority.NEVER);
gridPane.getColumnConstraints().addAll(columnConstraints0, columnConstraints1);
RowConstraints rowConstraints0 = new RowConstraints();
rowConstraints0.setVgrow(Priority.SOMETIMES);
gridPane.getRowConstraints().add(rowConstraints0);
Label someLabel = new Label("Some Label:");
ProgressBar progressBar = new ProgressBar();
progressBar.setPrefWidth(250.0d);
someLabel.setLabelFor(progressBar);
gridPane.add(someLabel, 0, 0);
gridPane.add(progressBar, 1, 0);
gridPane.setCursor(Cursor.HAND);
gridPane.setHgap(5.0d);
gridPane.setOnMouseClicked(event -> System.out.println("Clicked!"));
Scene scene = new Scene(gridPane, 350, 150);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

It would seem that the MouseEvent is being consumed. I had a quick look through the ProgressBar class and it would seem that the ProgressIndicatorSkin's BehaviourBase may be causing the event to be consumed.
A quick and dirty solution would be to set the mouse clicked EventHandler for the ProgressBar to re-fire the event to the GridPane:
progressBar.setOnMouseClicked(e -> gridPane.fireEvent(e));
or to work with any Parent node:
progressBar.setOnMouseClicked(e -> progressBar.getParent().fireEvent(e));
or subclass ProgressBar to automatically apply this behavior:
public class NoConsumeProgressBar extends ProgressBar {
public NoConsumeProgressBar() {
setOnMouseClicked(e -> {
Parent parent = getParent();
if (parent != null) {
parent.fireEvent(e);
}
});
}
}

Related

How do i display my MenuBar across all my scenes in JavaFX

I am new to JavaFX
I wrote this code however, I dont know how to Display the Menu Bar in all my Scenes. Also I would like to create/fill my scenes with the Layout in my HelloApplication (however thats another issue).
I have a controller, for setting the Stage and launching it.
My MenuBar is in the class MenuLeiste, but I would like it to appear in my Credits class aswell. Im very sorry for the lack of comments and the Layout of this comment.
public class HelloApplication extends Application {
public class Main {
public static void main(String[] args) {
launch(args);
}
}
#Override
public void start(Stage primaryStage) throws Exception {
//set window as primaryStage
Stage window = primaryStage;
//Layout of MenuLeiste is put in l1 and setted as scene1
MenuLeiste l1 = new MenuLeiste();
//menuscene gets its objects fromsceneViewMenu
Scene menuscene = new Scene(l1.sceneViewMenu());
window.setScene(menuscene);
window.setHeight(600);
window.setWidth(800);
window.setTitle("Game Title");
window.show();
}
}
My MenuLeiste class
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MenuLeiste {
public VBox sceneViewMenu() {
MenuBar menuBar = new MenuBar();
VBox menuBox = new VBox(menuBar);
Menu dataMenu = new Menu("Data");
MenuItem exitItem = new MenuItem("Exit");
exitItem.setOnAction(e -> System.exit(0));
Menu extrasMenu = new Menu("Extras");
MenuItem creditsItem = new MenuItem("Credits");
creditsItem.setOnAction(e -> {
Credits c = new Credits();
Scene scene3 = new Scene(c.sceneView3());
Stage window = (Stage) menuBox.getScene().getWindow();
window.setScene(scene3);
});
extrasMenu.getItems().addAll(creditsItem);
dataMenu.getItems().addAll( exitItem);
menuBar.getMenus().addAll(dataMenu,extrasMenu);
//the scenes layout is saved in layout1
VBox layout1 = new VBox(20);
layout1.getChildren().addAll(menuBox);
return layout1;
}
}
My Credits Class
package view;
import javafx.scene.Scene;`
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;`
public class Credits {
public VBox sceneView3()
{
Label label = new Label("Thanks");
Button backButton = new Button("Back");
backButton.setOnAction(e -> {
MenuLeiste l1 = new MenuLeiste();
Scene menuscene = new Scene(l1.sceneViewMenu());
Stage window = (Stage) backButton.getScene().getWindow();
window.setScene(menuscene);
});
VBox layout1 = new VBox(20);
layout1.getChildren().addAll(label, backButton);
return layout1;
}
}
When you want a node, or a group of nodes, to exist between different "scenes", often the best solution is to not replace the Scene. Instead, you'll want to modify the nodes displayed in the current scene. For example, in your case, you could have a BorderPane as the root of the scene with the MenuBar set as the top node. Then you replace the center node when you want to change the "view".
Here's a minimal runnable example demonstrating this concept. It makes use of "callbacks" to modify the center node of the BorderPane, while using the same MenuBar instance throughout. Though note the example only consists of views. If you have a backing model (i.e., data, business logic, etc.), you'll want to modify the code so you can pass it around. Also, if you write your application similarly to this example, it might be prudent to have all the views implement a common interface in a real application.
I don't have a separate "view class" for the menu bar, but that doesn't mean you can't have one (might even be better that way).
Main.java:
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
var root = new BorderPane();
root.setTop(createMenuBar(root::setCenter));
root.setCenter(new TitleView().getNode());
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.setTitle("Demo");
primaryStage.show();
}
private MenuBar createMenuBar(Consumer<Node> onUpdateView) {
var exitItem = new MenuItem("Exit");
exitItem.setOnAction(e -> Platform.exit());
var creditsItem = new MenuItem("Credits");
creditsItem.setOnAction(e -> {
e.consume();
var view = new CreditsView();
view.setOnGoBack(() -> onUpdateView.accept(new TitleView().getNode()));
onUpdateView.accept(view.getNode());
});
return new MenuBar(
new Menu("File", null, exitItem),
new Menu("Extras", null, creditsItem)
);
}
}
TitleView.java:
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
public class TitleView {
private Node node;
public Node getNode() {
if (node == null) {
node = new StackPane(new Label("Welcome!"));
}
return node;
}
}
CreditsView.java:
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
public class CreditsView {
private Runnable onGoBack;
private Node node;
public Node getNode() {
if (node == null) {
var stack = new StackPane();
stack.setPadding(new Insets(10));
var label = new Label("Credits View");
stack.getChildren().add(label);
var goBackBtn = new Button("Go back");
goBackBtn.setOnAction(e -> {
e.consume();
if (onGoBack != null) {
onGoBack.run();
}
});
stack.getChildren().add(goBackBtn);
StackPane.setAlignment(goBackBtn, Pos.TOP_LEFT);
node = stack;
}
return node;
}
public void setOnGoBack(Runnable action) {
onGoBack = action;
}
}
Here is some basic code that should be easy for a beginner to understand.
The main layout and the potential views to be displayed within it are created upfront.
A menu bar is placed at the top of the border pane in the main layout.
Menu items can be used to switch between views by setting the node to be currently displayed in the center of the border pane.
The existing views are reused rather than being recreated on each navigation.
You could not store references to existing views and create new views on each navigation if preferred.
The views themselves are just nodes, so the example could easily be adapted to use FXML because the output of the FXML loader is also a node. The same goes for anything else which may generate a node to be used as a view in this fashion.
Operation
The scene is initially displayed and the user clicks on the "View" menu to show the list of available views.
The user selects the "View Two" menu item and the second view is displayed. The application menu remains visible and can be used for future operations.
Sample Code
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class ViewSwitcherApp extends Application {
private BorderPane layout;
private final Node viewOne = new ViewOne();
private final Node viewTwo = new ViewTwo();
#Override
public void start(Stage stage) throws Exception {
// View menu
MenuItem viewOneMenuItem = new MenuItem("View One");
viewOneMenuItem.setOnAction(e -> setView(viewOne));
MenuItem viewTwoMenuItem = new MenuItem("View Two");
viewTwoMenuItem.setOnAction(e -> setView(viewTwo));
Menu viewMenu = new Menu(
"View", null,
viewOneMenuItem, viewTwoMenuItem
);
// File menu
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setOnAction(e -> Platform.exit());
Menu fileMenu = new Menu(
"File", null,
exitMenuItem
);
MenuBar menuBar = new MenuBar(
fileMenu, viewMenu
);
menuBar.setMinSize(MenuBar.USE_PREF_SIZE, MenuBar.USE_PREF_SIZE);
// Layout scene
layout = new BorderPane();
layout.setTop(menuBar);
setView(viewOne);
stage.setScene(
new Scene(layout, 300, 200)
);
stage.show();
}
private void setView(Node view) {
layout.setCenter(view);
}
public static void main(String[] args) {
launch(args);
}
}
class ViewOne extends StackPane {
public ViewOne() {
setStyle("-fx-background-color: lightblue; -fx-font-size: 30px;");
getChildren().add(new Label("View One"));
}
}
class ViewTwo extends StackPane {
public ViewTwo() {
setStyle("-fx-background-color: cornsilk; -fx-font-size: 30px;");
getChildren().add(new Label("View Two"));
}
}

JavaFX - Weird Behavior When Adding Node To Parent

I have created a simple app to simulate dynamic node creation with JAVAFX.
This app has the ability to create a new window whenever user want it by clicking the "New" button.
User can add a new node which is TitledPane to the window by clicking "Add Task" button and then clicking "Add" button on the dialog window.
There are an unexpected behavior which I want to fix. This app is only add new node (TitledPane in this case) to the last created window.
And the all of the nodes on the previous window will vanish.
You can see the following video to better understand what I mean.
VIDEO
https://youtu.be/eaWmu3zuuhE
NETBEANS PROJECT
Just in case you want to play with it.
https://drive.google.com/file/d/0B4Sbb8Ym-lcZLUIyWHV5ZXRSZE0/view?usp=sharing
CODES:
TasksList.java
package taskslist;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.stage.Stage;
public class TasksList extends Application {
DisplayWhich display = new DisplayWhich();
Stage primaryStage;
Parent startWindow;
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
initStart();
}
private void initStart(){
display.showDialogWindow();
}
public static void main(String[] args) {
launch(args);
}
}
TheList.java
package taskslist.view;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import taskslist.DisplayWhich;
public class TheList extends BorderPane {
public static VBox listWrapper;
public static ScrollPane listScroller;
public ObservableList<TitledPane> tasks;
private List<String> titles = new ArrayList<>();
public TheList(){
tasks = FXCollections.observableArrayList();
listWrapper = new VBox(5);
listScroller = new ScrollPane(listWrapper);
}
public void setTitles(String... title){
titles = Arrays.asList(title);
}
public List<String> getTitles(){
return titles;
}
public void loadSavedList(){
for(int i=0; i<getTitles().size();i++){
String ttlString = getTitles().get(i);
this.createTask(ttlString);
}
// Display Tasks
listWrapper.getChildren().addAll(this.tasks);
}
// Dialong for adding a new task and also editing a task
private void addTaskDialog(){
GridPane container = new GridPane();
Scene scene = new Scene(container, 150, 50);
Stage addNewTask = new Stage();
addNewTask.initModality(Modality.APPLICATION_MODAL);
addNewTask.setTitle("Add Task");
TextField title = new TextField();
Button confirm = new Button("Add");
// Create Task
confirm.setOnAction((ev) -> {
String ttlString = title.getText();
this.createTask(ttlString);
listWrapper.getChildren().clear();
listWrapper.getChildren().addAll(this.tasks);
addNewTask.close();
});
container.add(title, 0, 1);
container.add(confirm, 0, 5);
addNewTask.setScene(scene);
addNewTask.showAndWait();
}
// Assemble all this.tasks list components
public void render(){
setCenter(listScroller);
loadSavedList();
Button newProject = new Button("New");
Button addTask = new Button("Add Task");
BorderPane listBottom = new BorderPane();
HBox bottomLeft = new HBox();
bottomLeft.getChildren().add(newProject);
listBottom.setLeft(bottomLeft);
HBox bottomRight = new HBox();
bottomRight.getChildren().add(addTask);
listBottom.setRight(bottomRight);
newProject.setOnAction((evt) -> {
DisplayWhich display = new DisplayWhich();
display.showDialogWindow();
});
addTask.setOnAction((e) -> {
addTaskDialog();
});
setBottom(listBottom);
}
// Cteate task from strings
private void createTask(String... strings){
String taskTitle = strings.length > 0 ? strings[0] : "";
TitledPane task = new TitledPane();
task.setPrefWidth(647);
task.setExpanded(false);
task.setText(taskTitle);
this.tasks.add(task);
}
}
NewDialog.java
package taskslist.view;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import taskslist.DisplayWhich;
public class NewDialog {
DisplayWhich display = new DisplayWhich();
Stage stage = new Stage();
Parent startWindow = new AnchorPane();
#FXML
private Button cancelNew;
#FXML
private Button confirmCreation;
/**
* Initializes the controller class.
*/
#FXML
private void initialize() {
}
#FXML
private void cancelNewCreation(ActionEvent event) {
((Stage)cancelNew.getScene().getWindow()).close();
}
#FXML
private void confirmCreateNew(ActionEvent event) {
((Stage)confirmCreation.getScene().getWindow()).close();
TheList wrap = new TheList();
TheWindow window = new TheWindow();
window.makeWindow(wrap);
wrap.setTitles("one", "two", "three", "four");
wrap.render();
}
}
DisplayWhich.java
package taskslist;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import taskslist.view.TheList;
public class DisplayWhich {
Stage stage = new Stage();
Parent startWindow = new AnchorPane();
public DisplayWhich(){}
public Stage showDialogWindow(){
try {
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Create New Project");
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/taskslist/view/newDialog.fxml"));
startWindow = loader.load();
Scene scene = new Scene(startWindow);
stage.setScene(scene);
stage.setOnCloseRequest((event) -> {
System.out.println("test");
});
stage.showAndWait();
} catch (IOException ex) {
ex.printStackTrace();
}
return stage;
}
}
TheWindow.java
package taskslist.view;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TheWindow {
public TheWindow(){}
public void makeWindow(BorderPane group) {
Stage mainWindow = new Stage();
Scene scene = new Scene(group, 650, 550);
mainWindow.setScene(scene);
mainWindow.setTitle("Task List");
mainWindow.centerOnScreen();
mainWindow.show();
}
}
Why that weird behavior happening and how to fix it so it only adds new node to the same window where the clicked "Add Task" button is located?
These fields should not be static:
public static VBox listWrapper;
public static ScrollPane listScroller;

How do i make my counter appear in my application through javaFX

I'm new to javaFX and I wanted to make a simple code that counted how many times a person pressed a button and displayed the count on the application itself. Currently I have my code printing the counter in my IDE and would just like to some how attach it to the scene(eg I click run and every time I click the button it prints how many times I've clicked it in my workbench). I looked around stack overflow and youtube but the closest I got to what I was looking for was printing it in my IDE. Thanks for any help.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXTest extends Application {
private int counter = 0;
public static void main (String [] args){
Application.launch();
}
#Override
public void start(Stage primaryStage) throws Exception {
Stage stage = new Stage();
stage = primaryStage;
Pane pane = new Pane();
pane.setPrefSize(400,400);
Button button = new Button("Smash it!");
HBox root = new HBox(5, pane);
button.setOnAction(e -> {
counter();
});
root.getChildren().add(button);
Scene scene1 = new Scene(root,1000, 800, Color.AQUA);
stage.setScene(scene1);
stage.setTitle("ButtonSmash!");
stage.show();
}
public void counter(){
counter++;
System.out.println(counter);
}
}
Here is the full code:
package StackOverFlow;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXTest extends Application {
private int counter = 0;
private Label label = new Label("Count: ");
public static void main (String [] args){
Application.launch();
}
#Override
public void start(Stage primaryStage) throws Exception {
Stage stage = new Stage();
stage = primaryStage;
Pane pane = new Pane();
pane.setPrefSize(400,400);
Button button = new Button("Smash it!");
HBox root = new HBox(5, pane);
button.setOnAction(e -> {
label.setText("Count: "+Integer.toString(counter));
counter();
});
root.getChildren().add(button);
label.relocate(0, 0); // You can put this label, wherever you want!
root.getChildren().add(label);
Scene scene1 = new Scene(root,1000, 800, Color.AQUA);
stage.setScene(scene1);
stage.setTitle("ButtonSmash!");
stage.show();
}
public void counter(){
counter++;
//System.out.println(counter);
}
}
You had to make one label and to add it to your pane.getChildren();
And whenever you press the button you need to change text from that label.

Put a Scrollbar into to Pane JavaFX

I'm just working on a little project and started to get in JavaFX.
I have a problem and I don't know any solutions..
So I managed it to bring a Scrollbar(incl Listener) into the root.
But the listener doesn't work.
I want to add many comboboxes one below the other and when I reached the scenesize(LayoutX) it should be possible to scrolldown.
How can I solve my problem?
package application;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.*;
import javafx.stage.Stage;
import application.XMLActions;;
public class Main extends Application {
/**
* Globale Variablen
*/
int abstandszaehler = 0;
private Pane root = new Pane();
private ScrollBar sB = new ScrollBar();
private XMLActions xA = new XMLActions();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("XML-Zeilenersteller");
primaryStage.setResizable(false);
/**
* Elemente für die Root
*/
//Buttons
Button newXMLLine = new Button();
newXMLLine.setText("Einfügen neuer XML-Zeile");
newXMLLine.setLayoutX(735);
newXMLLine.setLayoutY(80);
newXMLLine.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
setComboBox();
}
});
Button newXMLDocument = new Button();
newXMLDocument.setText("Erstelle XML-Dokument");
newXMLDocument.setLayoutX(735);
newXMLDocument.setLayoutY(550);
newXMLDocument.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Test2");
}
});
//Überschrift
Text header = new Text(105, 50, "XML Lines Creator");
header.setFont(new Font(30)); header.setStyle("-fx-underline: true;");
//Scrollbar
sB.setLayoutX(715);
sB.setLayoutY(80);
sB.setMin(0);
sB.setOrientation(Orientation.VERTICAL);
sB.setPrefHeight(500);
sB.setMax(360);
sB.setUnitIncrement(30);
sB.setBlockIncrement(35);
sB.valueProperty().addListener((ObservableValue<? extends Number> ov,
Number old_val, Number new_val) -> {
System.out.println(-new_val.doubleValue());
});
/**
* Hauptseite als Root
* Rootbearbeitungen
*/
root.setStyle("-fx-background-color: lightsteelblue");
root.getChildren().addAll(sB,newXMLDocument,header,newXMLLine );
//Scene setzen
Scene mainScene = new Scene(root, 900, 600);
primaryStage.setScene(mainScene);
primaryStage.show();
}
public void setComboBox(){
ComboBox cB = new ComboBox(xA.getList());
root.getChildren().add(cB);
cB.setLayoutX(80);
cB.setLayoutY(80 + abstandszaehler);
abstandszaehler = abstandszaehler + 30;
}
}
EDIT 1:
I got a little progress with that code in the listener:
root.setLayoutY(-new_val.doubleValue());
Replace the Pane with a ScrollPane. On the ScrollPane you can define the policy for your scrollbar.
If you define it like this, it will behave like a Pane:
ScrollPane sp = new ScrollPane();
sp.setHbarPolicy(ScrollBarPolicy.NEVER);
sp.setVbarPolicy(ScrollBarPolicy.NEVER);
Take a look at this article by Oracle.
First, if you wish to layout controls vertically consider using VBox. This VBox should then be enclosed by a ScrollPane.
If you then set the VBox's prefHeight to Control.USE_COMPUTED_SIZE and maxHeight to Double.POSITIVE_INFINITY the VBox should resize to fit it's content without limit, and the enclosing ScrollPane should show and hide scrollbars as necessary.

Place button on top of webView in GridPane

I want to create a refresh button for my webView that will be on top of the view (even if it hides part of the view), when I place the button on the Grid Pane it pushes the webView down or to the side (depends where I place the button)
How can I place my "refresh" button on top of the webView and not move it aside?
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class webviewbrowser extends Application {
#Override public void start(Stage primaryStage) throws Exception {
Pane root = new WebViewPane();
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.setFullScreen(true);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
/**
* Create a resizable WebView pane
*/
public class WebViewPane extends Pane {
public WebViewPane() {
VBox.setVgrow(this, Priority.ALWAYS);
setMaxWidth(Double.MAX_VALUE);
setMaxHeight(Double.MAX_VALUE);
WebView view = new WebView();
view.setMinSize(500, 400);
view.setPrefSize(500, 400);
final WebEngine eng = view.getEngine();
eng.load("http://google.com");
//final TextField locationField = new TextField("http://www.google.com");
//locationField.setMaxHeight(Double.MAX_VALUE);
Button goButton = new Button("Refresh");
goButton.setDefaultButton(true);
EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
eng.reload();
}
};
goButton.setOnAction(goAction);
GridPane grid = new GridPane();
grid.setVgap(0);
grid.setHgap(0);
GridPane.setConstraints(goButton,2,0,2,1, HPos.RIGHT, VPos.BOTTOM, Priority.ALWAYS, Priority.ALWAYS);
GridPane.setConstraints(view, 0, 0, 2, 1, HPos.CENTER, VPos.CENTER, Priority.SOMETIMES, Priority.SOMETIMES);
grid.getColumnConstraints().addAll(
new ColumnConstraints(100, 100, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true),
new ColumnConstraints(40, 40, 40, Priority.NEVER, HPos.CENTER, true)
);
grid.getChildren().addAll(goButton, view);
getChildren().add(grid);
}
#Override protected void layoutChildren() {
List<Node> managed = getManagedChildren();
double width = getWidth();
double height = getHeight();
double top = getInsets().getTop();
double right = getInsets().getRight();
double left = getInsets().getLeft();
double bottom = getInsets().getBottom();
for (int i = 0; i < managed.size(); i++) {
Node child = managed.get(i);
layoutInArea(child, left, top,
width - left - right, height - top - bottom,
0, Insets.EMPTY, true, true, HPos.CENTER, VPos.CENTER);
}
}
}
}
If you want to stack one component on top of another, don't use a GridPane for layout, instead use a parent that allows layout components to be placed on top of one another. For example, a standard Pane, a StackPane, Group or Region. In these stacked style layouts, the components are rendered in order of the child component's position in the parent's child list.
In your sample code you are already extending Pane, so get rid of all of the grid code and just do:
getChildren().addAll(view, goButton);
instead of:
grid.getChildren().addAll(goButton, view);
Modify the layout properties of your goButton to position it within a parent which does not manage the layout position of it's children, e.g. you can call goButton.relocate(xPos, yPos).
You have some custom stuff in the layoutChildren method you override that may mess up the default Pane layout processing logic. Overriding layoutChildren is more of an advanced layout topic and I wouldn't advise it for beginners.
Here is an updated sample you could look at which uses some of the concepts mentioned in this answer.
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.web.*;
import javafx.stage.Stage;
public class WebViewBrowser extends Application {
#Override public void start(Stage stage) throws Exception {
stage.setScene(new Scene(new WebViewPane("http://google.com")));
stage.setFullScreen(true);
stage.show();
}
public static void main(String[] args) { launch(args); }
}
class WebViewPane extends Pane {
final WebView view = new WebView();
final Button goButton = createGoButton(view.getEngine());
public WebViewPane(String initURL) {
view.getEngine().load(initURL);
getChildren().addAll(
view,
goButton
);
initLayout();
}
private Button createGoButton(final WebEngine eng) {
Button go = new Button("Refresh");
go.setDefaultButton(true);
go.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
eng.reload();
}
});
return go;
}
private void initLayout() {
setMinSize(500, 400);
setPrefSize(1024, 768);
view.prefWidthProperty().bind(widthProperty());
view.prefHeightProperty().bind(heightProperty());
goButton.setLayoutX(10);
goButton.layoutYProperty().bind(
heightProperty().subtract(20).subtract(goButton.heightProperty())
);
}
}

Categories

Resources