Can't access button/textarea in the handle event - java

I've just started using JavaFX and have been trying to add an event that will add text to a textarea and clear a text field when you press the 'send' button. However, I can't seem to check the source of the event in the handle method.
I've tried to search for a solution, but others don't seem to face the same issue - either that or I'm missing something obvious.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ApplicationMain extends Application implements EventHandler<ActionEvent>{
Stage window;
// Main Method
public static void main(String[] args) {
launch(args);
}
// Scene Method
#SuppressWarnings("static-access")
#Override
public void start(Stage primaryStage) {
// Window Stuff
window = primaryStage;
window.setTitle("Chat Application");
// Setup Grid Layout
GridPane grid = new GridPane();
grid.setAlignment(Pos.TOP_LEFT);
grid.setHgap(10);
grid.setStyle("-fx-background-color: #272828;");
// MenuBar
MenuBar menu = new MenuBar();
menu.setPrefWidth(1000);
menu.setPrefHeight(20);
// Creation of File + Help
Menu file = new Menu("File");
Menu help = new Menu("Help");
// Add the Menus to the MenuBar
menu.getMenus().add(file);
menu.getMenus().add(help);
// Add MenuBar to Scene
menu.setVisible(true);
grid.add(menu, 0, 0);
// Text Area Stuff
TextArea area = new TextArea();
area.setPrefWidth(1000);
area.setPrefHeight(700);
area.setEditable(false);
area.setStyle("-fx-control-inner-background: #313233;");
// Add Text Area to Grid
grid.add(area, 0, 1);
// Text Field
TextField enter = new TextField();
enter.setPromptText("Type here...");
enter.setMaxWidth(920);
enter.setMaxHeight(30);
enter.setStyle("-fx-padding: 5px;");
// Button
Button send = new Button("Send!");
// Set the Handler for the Send Button Event
send.setOnAction(this);
// Use of HBox to Space out Text Field & Send Button
HBox row = new HBox();
row.setSpacing(10);
row.setHgrow(enter, Priority.ALWAYS);
row.getChildren().addAll(enter, send);
// Use of VBox to Space out Text Field
VBox box = new VBox();
box.setSpacing(10);
box.setPadding(new Insets(10));
box.getChildren().add(row);
// Add HBox in VBox to Grid
grid.add(box, 0, 2);
// Scene Stuff
Scene scene = new Scene(grid, 1000, 750);
window.setScene(scene);
// Display the Window
window.show();
}
// Event Handler
#Override
public void handle(ActionEvent event) {
if (event.getSource() == send) {
}
}
}
Whenever I try to check if the source was the button 'send', it doesn't show up - as if it's not accessible by the method. I'm unsure of how to fix this.

There is a few things wrong with this code but we can fix it no problemo.
First learn naming conventions and stick to them as #kleopatra says if you google java naming conventions you will be overloaded with many results read a few
Next you shouldn't call a Stage a window there is already another object that has that name so it may confuse others but if its only for you its ok I guess
I wouldn't #SuppressWarnings("static-access") as you have done if you have an error fix it don't ignore it
The send.setOnAction(this); is not the way to handle events remove your implements EventHandler<ActionEvent> you can use the event handler by setting it like this
send.setOnAction(event -> sendToTextArea(enter.getText(), area));
And this is what the method you are calling should look like
private void sendToTextArea(String string, TextArea textArea){
//textArea.setText(string);Use setText if you want to set the whole area to something
textArea.appendText(string+"\n");//Use appendText to append add new line because chat app
}
Eveything else looks good here is what your final product should look like
public class Main extends Application {
private Stage stage;
#Override
public void start(Stage primaryStage) {
// stage Stuff
stage = primaryStage;
stage.setTitle("Chat Application");
// Setup Grid Layout
GridPane grid = new GridPane();
grid.setAlignment(Pos.TOP_LEFT);
grid.setHgap(10);
grid.setStyle("-fx-background-color: #272828;");
// MenuBar
MenuBar menu = new MenuBar();
menu.setPrefWidth(1000);
menu.setPrefHeight(20);
// Creation of File + Help
Menu file = new Menu("File");
Menu help = new Menu("Help");
// Add the Menus to the MenuBar
menu.getMenus().add(file);
menu.getMenus().add(help);
// Add MenuBar to Scene
menu.setVisible(true);
grid.add(menu, 0, 0);
// Text Area Stuff
TextArea area = new TextArea();
area.setPrefWidth(1000);
area.setPrefHeight(700);
area.setEditable(false);
area.setStyle("-fx-control-inner-background: #313233;");
// Add Text Area to Grid
grid.add(area, 0, 1);
// Text Field
TextField enter = new TextField();
enter.setPromptText("Type here...");
enter.setMaxWidth(920);
enter.setMaxHeight(30);
enter.setStyle("-fx-padding: 5px;");
// Button
Button send = new Button("Send!");
// Set the Handler for the Send Button Event
send.setOnAction(event -> sendToTextArea(enter, area));
// Use of HBox to Space out Text Field & Send Button
HBox row = new HBox();
row.setSpacing(10);
row.setHgrow(enter, Priority.ALWAYS);
row.getChildren().addAll(enter, send);
// Use of VBox to Space out Text Field
VBox box = new VBox();
box.setSpacing(10);
box.setPadding(new Insets(10));
box.getChildren().add(row);
// Add HBox in VBox to Grid
grid.add(box, 0, 2);
// Scene Stuff
Scene scene = new Scene(grid, 1000, 750);
stage.setScene(scene);
// Display the stage
stage.show();
}
private void sendToTextArea(TextField textField, TextArea textArea){
//textArea.setText(string);Use setText if you want to set the whole area to something
//textArea.clear();and .clear to clear all text from the TextArea
textArea.appendText(textField.getText()+"\n");//Use appendText to append add new line because chat app
textField.clear();
}
public static void main(String[] args) { launch(args); }
}

Make your TextArea and TextField class variables:
private TextArea area;
private TextField enter;
Change their initialization:
// Text Area Stuff
area = new TextArea();
// Text Field
enter = new TextField();
And your event handler :
// Event Handler
#Override
public void handle(ActionEvent event) {
area.setText(enter.getText());
}
If any of these changes is not clear, do not hesitate to ask.

Related

Show other window when click button JavaFX

I want to solve my homework and I don't know how to start; the goal is to make 2 GUI Forms in JavaFX. The 1st is home form that contains Button1, and when the user clicks Button1 : show the 2nd Form and close the 1st.
How to do that ? hope to give me examples.
Thanks for reading and helping.
You can do something like this, but please keep in mind that we learn via practicing and training, try to do your own one after having a look at the idea in this example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class TwoForms extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane(); // TLC (Top Layer Container) a root container for all other components, which in your case is the Button
Button button = new Button("Go To Second Form"); // the button
root.getChildren().add(button); // add the button to the root
Scene scene = new Scene(root, 500,500); // create the scene and set the root, width and height
primaryStage.setScene(scene); // set the scene
primaryStage.setTitle("First Form");
primaryStage.show();
// add action listener, I will use the lambda style (which is data and code at the same time, read more about it in Oracle documentation)
button.setOnAction(e->{
//primaryStage.close(); // you can close the first stage from the beginning
// create the structure again for the second GUI
// Note that you CAN use the previous root and scene and just create a new Stage
//(of course you need to remove the button first from the root like this, root.getChildren().remove(0); at index 0)
StackPane root2 = new StackPane();
Label label = new Label("Your are now in the second form");
root2.getChildren().add(label);
Scene secondScene = new Scene(root2, 500,500);
Stage secondStage = new Stage();
secondStage.setScene(secondScene); // set the scene
secondStage.setTitle("Second Form");
secondStage.show();
primaryStage.close(); // close the first stage (Window)
});
}
public static void main(String[] args) {
launch();
}
}
Result
After Clicking on the Button -> Second Window.

Set Action on button to do two action in one click

Here is the scenario, I have a main window and I click on one button it opens a pop up window. In this pop window I have table view that have some data display in it, and it have a one button called select. After select the data from table view, so when I push the select button I want this pop window to close and the data I selected from that to appear in my main window.
So far only thing I can do is extract the data from pop up window, I want it to close aswell with just one click
private void venueDisplay(String title, String message) {
Stage window = new Stage();
//Block events to other windows
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle(title);
window.setMinWidth(400);
HBox hBox = new HBox();
hBox.setPadding(new Insets(10,10,10,10));
hBox.setSpacing(10);
hBox.setMaxHeight(20);
hBox.setAlignment(Pos.BOTTOM_CENTER);
hBox.getChildren().add(selectVenueButton);
//Display all the available venues to choose for allocation
VBox layout = new VBox(10);
venueList = new ListView<>();
ObservableList<Venue> observableVenue = FXCollections.observableArrayList(model.getVenues());
venueList.setItems(observableVenue);
layout.getChildren().addAll(venueList, hBox);
//Display window and wait for it to be closed before returning
Scene scene1 = new Scene(layout,300,500);
window.setScene(scene1);
window.showAndWait();
}
public void selectButtonHandler(EventHandler<ActionEvent> handler) {
selectVenueButton.setOnAction(handler);
}
Please consider this Example, you may take the idea and apply it to your program (Explanation in Comments).
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class GetInfoFromPopUpWindow extends Application{
static TextArea textArea = new TextArea(); // to be filled from the pop-up window
#Override
public void start(Stage primaryStage) throws Exception {
// create the main Window and some simple components
// Suppose it contains a TextArea only for simplicity sake
Button open = new Button("Open Popup Window");
//simple container as a root for testing
HBox root = new HBox();
root.getChildren().addAll(textArea, open);
Scene scene = new Scene(root,610,400);
primaryStage.setScene(scene);
primaryStage.setTitle("Main Window");
primaryStage.show();
//Add Action Listener to the open Button
open.setOnAction(e->{ // lambda expression, read more about it in the Documentation
popUpWindow(); // call the method to open a pop-up wondow(see later)
});
}
public static void popUpWindow(){
VBox root = new VBox();
Button fetchInfo = new Button("Finish");
//create a listView and populate it with some info for testing purpose
// suppose the info you get from some database
ListView<String> listView = new ListView<String>();
ObservableList<String> items = FXCollections.observableArrayList (
"First Item", "Second Item", "Third Item", "Fourth Item");
listView.setItems(items);
//to select more than one item
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
//decoration and size are up to your preference
listView.setPrefWidth(100);
listView.setPrefHeight(100);
root.getChildren().addAll(listView, fetchInfo);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 250,150);
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(scene);
stage.setTitle("Popup Window");
stage.show();
// Add action listener to fetchInfo Button in this Window
fetchInfo.setOnAction(e->{
// take the info from listView and fill it in the TextArea in the main Window
// just for testing purposes
for (String selectedItem : listView.getSelectionModel().getSelectedItems()){
textArea.appendText(selectedItem + " \n");
}
// when it finishes -> close the window and back to the first one
stage.close();
});
}
public static void main(String[] args) {
launch();
}
}
Test
Main Window Before Clicking Any Button
The Pop-Up Window After Clicking On The Button And Selecting Some Items
After Clicking on Finish Button, It Closes The Pop-Up Window and Then Goes Back To Main Menu With The Information (Selected Items)
I think you can just do:
private Venue venueDisplay(String title, String message) {
// existing code..
window.showAndWait();
return venueList.getSelectionModel().getSelectedItem();
}
and then your selectVenueButton just needs to close the window:
selectVenueButton.setOnAction(e -> window.hide());
you want to perform two operation on click select button
Close popup window :
To achieve this set Event Handler on button as below
selectVenueButton.setOnAction(handler);
In handler you can write logic to close popup window as below :
private EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Object source = event.getSource();
if (source instanceof Button) {
Button btn = (Button) source;
Stage stage = (Stage) btn.getScene().getWindow();
stage.close();
}
}
};
After click on button you want selected data on main window :
To achieve this declare venue list on Class Level Scope (Member Variables), so you can access outside a class.
in Dialog class :
ListView<Venue> venueList;
Access data in main Window :
CustomDialog dialog = new CustomDialog(); //popup class
dialog.showDialog;
Venue selectedItem = dialog.venueList.getSelectionModel().getSelectedItems();

Using JavaFX to build a GUI for an ATM but having trouble getting primary stage to change scene

Trying to use event handlers to sync specific button pushes to advance to the next "screen" on an ATM by: hiding the stage, updating the stage with the scene that a button push creates, and then reshowing the stage.
I am curious if this process can only be taken so deep since my button for newCheckingsAccounts isn't doing anything like it should, but I can go backwards on that page and I used the same code more or less to try to keep going forward.
import java.awt.Insets;
import java.util.ArrayList;
import java.util.Scanner;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class TestAccount extends Application {
//creates arrays that will store the accounts
ArrayList<Account> Checking = new ArrayList<Account>();
ArrayList<Integer> Savings = new ArrayList<Integer>();
//declares variables
double interest = 0;
double interestRate = 0;
double balance = 0;
double credit = 0;
double initialBalance = 0;
double feeChargedPerTransaction = 0;
Button btMain = new Button("Go Back to Main Menu");
Button btNewAccount = new Button("Make New Account");
Button btExistingAccount = new Button("Access an Existing Account");
Button btNewCheckings = new Button("Make New Checkings");
Button btNewSavings = new Button("Make New Savings");
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Hold two buttons in an HBox
HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btGoToAccounts = new Button("Go To Accounts Page");
Button btEnd = new Button("End Program");
hBox.getChildren().add(btGoToAccounts);
hBox.getChildren().add(btEnd);
BorderPane borderPane = new BorderPane();
borderPane.setBottom(hBox);
BorderPane.setAlignment(hBox, Pos.CENTER);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 500, 300);
primaryStage.setTitle("Bank of America"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
// creates and registers handler and specifies action for button to go to accounts page
btGoToAccounts.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
primaryStage.hide();
// Hold three buttons in an HBox
HBox hBox1 = new HBox();
hBox1.setSpacing(10);
hBox1.setAlignment(Pos.CENTER);
hBox1.getChildren().add(btNewAccount);
hBox1.getChildren().add(btExistingAccount);
hBox1.getChildren().add(btMain);
BorderPane borderPane1 = new BorderPane();
borderPane1.setBottom(hBox1);
BorderPane.setAlignment(hBox1, Pos.CENTER);
Scene scene1 = new Scene(borderPane1, 500, 300);
primaryStage.setTitle("Accounts Page"); // Set the stage title
primaryStage.setScene(scene1); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
});
// creates and registers handler and specifies action for button to go to create new accounts page
btNewAccount.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
primaryStage.hide();
// Hold three buttons in an HBox
HBox hBox2 = new HBox();
hBox2.setSpacing(10);
hBox2.setAlignment(Pos.CENTER);
Button btNewCheckings = new Button("Make New Checkings");
Button btNewSavings = new Button("Make New Savings");
hBox2.getChildren().add(btNewCheckings);
hBox2.getChildren().add(btNewSavings);
hBox2.getChildren().add(btMain);
BorderPane borderPane2 = new BorderPane();
borderPane2.setBottom(hBox2);
BorderPane.setAlignment(hBox2, Pos.CENTER);
Scene scene2 = new Scene(borderPane2, 800, 300);
primaryStage.setTitle("New Accounts"); // Set the stage title
primaryStage.setScene(scene2); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
});
// THIS IS THE BUTTON THAT DOESN'T REGISTER AS BEING CLICKED...havent done the newSavingsAccount button either.want it to take me to new scene where i enter in new account info hit submit and then take me back to the main menu ("scene")
btNewCheckings.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
HBox hbox3 = new HBox();
Scene scene3 = new Scene(hbox3, 800, 300);
primaryStage.setTitle("Test"); // Set the stage title
primaryStage.setScene(scene3); // Place the scene in the stage
//the Name text field
final TextField name = new TextField();
name.setPromptText("Enter the desired account name which will be used under the access an existing account screen later");
name.setPrefColumnCount(10);
name.getText();
hbox3.getChildren().add(name);
//Defining the initial balance/fee text fields
final TextField initialBalance = new TextField();
final TextField fee = new TextField();
initialBalance.setPromptText("Enter your desired initial balance as a double.");
fee.setPromptText("Enter the agreed upon fee per transaction as a double.");
initialBalance.setPrefColumnCount(15);
fee.setPrefColumnCount(15);
fee.getText();
hbox3.getChildren().add(fee);
initialBalance.getText();
hbox3.getChildren().add(initialBalance);
//Defining the Submit button
Button accountCreation = new Button("Create the Account");
hbox3.getChildren().add(accountCreation);
//Defining the Clear button
Button clear = new Button("Clear");
hbox3.getChildren().add(clear);
primaryStage.show(); // Display the stage
//Setting an action for the Submit button
accountCreation.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
if ((initialBalance.getText() != null && !initialBalance.getText().isEmpty())) {
CheckingAccount newMember = new CheckingAccount();
newMember.setInitialBalance(Double.parseDouble(initialBalance.toString()));
newMember.setFee((Double.parseDouble(fee.toString())));
Checking.add(newMember);
} else {
System.out.println("no member added");
}
}
});
//Setting an action for the Clear button
clear.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
name.clear();
initialBalance.clear();
}
});
}
});
// creates and registers handler and specifies action for end button to close the stage
btEnd.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
primaryStage.close();
}
});
// creates and registers handler and specifies action for main menu button to go to first scene
btMain.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
primaryStage.hide();
primaryStage.setTitle("Bank of America"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
});
}
/**
* 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);
}
}
I think removing the overriding of your both buttons in the btNewAccount.setOnAction() should solve your problem:
// creates and registers handler and specifies action for button to go
// to create new accounts page
btNewAccount.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.hide();
// Hold three buttons in an HBox
HBox hBox2 = new HBox();
hBox2.setSpacing(10);
hBox2.setAlignment(Pos.CENTER);
// ############### removed this ###################
//Button btNewCheckings = new Button("Make New Checkings");
//Button btNewSavings = new Button("Make New Savings");
hBox2.getChildren().add(btNewCheckings);
hBox2.getChildren().add(btNewSavings);
hBox2.getChildren().add(btMain);
BorderPane borderPane2 = new BorderPane();
borderPane2.setBottom(hBox2);
BorderPane.setAlignment(hBox2, Pos.CENTER);
Scene scene2 = new Scene(borderPane2, 400, 300);
primaryStage.setTitle("New Accounts"); // Set the stage title
primaryStage.setScene(scene2); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
});
If you want to instantiate in an ActionHandler of a Button, you need to declare it's ActionHandler in the same Block.
The way you did it (ActionHandler in the start method), it will only work, if you use your class atributes (Buttons) which you have initialized at the top.
Hope I could help :)
Edit: Probably a good tip for this project is looking at FXML files with JavaFX. This might help you: http://code.makery.ch/library/javafx-8-tutorial/part1/

How do I set up two vertical split panes so that dragging each will not affect the other?

I am trying to set up a UI with three split panes. The first two are vertical panes, on the left and right side of the screen. One side of each split has a title pane. The user can select items from these panes to include in fields in the central pane. There is also a horizontal pane at the bottom that is not relevant to this question.
The user can open these side panes either by dragging the vertical dividers, or by clicking on the relevant toggle button (Films, Books etc.) to show that pane.
The issue I have is that I want to make it so that dragging one vertical divider does not move the other. However, since I cannot find a way to set this up without putting one of the vertical split panes into the other vertical pane, this always results in a situation where moving one of the dividers also moves the other. In the case of the below code for instance, moving the vertical divider for the left-hand (Films) split pane moves the right-hand vertical divider.
Can anyone help with this?
package pane2;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.application.*;
import javafx.beans.property.DoubleProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TitledPane;
import javafx.scene.input.*;
import javafx.stage.Stage;
public class Pane2 extends Application {
SplitPane rightSplit;
DoubleProperty rightSplitDividerPos;
TitledPane books;
ToggleButton selectBooks;
VBox booksBox;
VBox centre;
SplitPane leftSplit;
DoubleProperty leftSplitDividerPos;
TitledPane films;
ToggleButton selectFilms;
VBox filmsBox;
VBox centreLeft;
SplitPane mainSplit;
DoubleProperty mainSplitDividerPos;
TitledPane arts;
ToggleButton selectArts;
VBox artsBox;
BorderPane root;
public static void main(String[] args)
{
launch( args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Test");
//Create right-hand titled pane for the books list and centre it in Vbox
books = new TitledPane();
books.setText("Books");
books.setMinWidth(0);
booksBox = new VBox(0,books);
//Create central pane and add toggle buttons to open hidden panes on the
//left, right, and bottom (films, books, and arts respectively)
selectBooks = new ToggleButton("Books");
selectFilms = new ToggleButton("Films");
selectArts = new ToggleButton("Arts");
centre = new VBox(100,selectBooks,selectFilms,selectArts);
centre.setPrefWidth(1300);
centre.setPrefHeight(750);
//Create split pane to divide the central pane and books list
rightSplit = new SplitPane();
rightSplit.getItems().addAll(centre,booksBox);
//Create left-hand titled pane for the films list and centre it in VBox
films = new TitledPane();
films.setText("Films");
films.setMinWidth(0);
filmsBox = new VBox(0,films);
//Create split pane to divide the films list and the central pane
leftSplit = new SplitPane();
leftSplit.getItems().addAll(filmsBox,rightSplit);
//Create mainSplit pane
arts = new TitledPane();
arts.setText("arts");
arts.setMinHeight(0);
artsBox = new VBox(0,arts);
mainSplit = new SplitPane();
mainSplit.setOrientation(Orientation.VERTICAL);
mainSplit.getItems().addAll(leftSplit,artsBox);
root = new BorderPane();
root.setCenter(mainSplit);
//Set divider positions for the three dividers
rightSplitDividerPos = rightSplit.getDividers().get(0).positionProperty();
rightSplitDividerPos.set(1.0);
leftSplitDividerPos = leftSplit.getDividers().get(0).positionProperty();
leftSplitDividerPos.set(0.0);
mainSplitDividerPos = mainSplit.getDividers().get(0).positionProperty();
mainSplitDividerPos.set(1.0);
//Start up scene and stage
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.show();
//Event - if the books toggle button is selected, the left divider will
//move to the right to show the books selection pane
selectBooks.setOnAction(event -> {
if(selectBooks.isSelected()){
leftSplitDividerPos.set(0.15);
}
if(!selectBooks.isSelected()){
leftSplitDividerPos.set(0.0);
}else{
}
});
//Event - if the films toggle button is selected, the right divider will
//move to the left to show the films selection pane
selectFilms.setOnAction(event -> {
if(selectFilms.isSelected()){
rightSplitDividerPos.set(0.8);
}
if(!selectFilms.isSelected()){
rightSplitDividerPos.set(1.0);
}else{
}
});
//Event - if the arts toggle button is selected, the bottom divider will
//move up to show the arts selection pane
selectArts.setOnAction(event -> {
if(selectArts.isSelected()){
mainSplitDividerPos.set(0.75);
}
if(!selectArts.isSelected()){
mainSplitDividerPos.set(1.0);
}else{
}
});
}
}
do you really need 3 SplitPane in your layout? because i think you can achieve pretty much the same result with just 1 pane:
SplitPane split = new SplitPane();
VBox left = new VBox(new Label("left"));
left.setStyle("-fx-background-color: cadetblue");
VBox right = new VBox(new Label("right"));
right.setStyle("-fx-background-color: darkorange");
VBox center = new VBox(new Label("center"));
center.setStyle("-fx-background-color: darkgreen");
split.getItems().addAll(left, center, right);
split.setDividerPosition(0,1/(double)3);
split.setDividerPosition(1,2/(double)3);
Scene scene = new Scene(split, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
Here is your code realated Example:
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Test");
//Create central pane and add toggle buttons to open hidden panes on the
//left, right, and bottom (films, books, and arts respectively)
ToggleButton selectBooks = new ToggleButton("Books");
ToggleButton selectFilms = new ToggleButton("Films");
ToggleButton selectArts = new ToggleButton("Arts");
VBox centre = new VBox(100,selectBooks,selectFilms,selectArts);
//Create left-hand titled pane for the films list and centre it in VBox
TitledPane films = new TitledPane();
films.setText("Films");
VBox filmsBox = new VBox(films);
//Create right-hand titled pane for the books list and centre it in Vbox
TitledPane books = new TitledPane();
books.setText("Books");
VBox booksBox = new VBox(books);
//Create mainSplit pane
TitledPane arts = new TitledPane();
arts.setText("arts");
VBox artsBox = new VBox(arts);
SplitPane mainSplit = new SplitPane();
mainSplit.getItems().addAll(filmsBox, centre, booksBox);
mainSplit.setDividerPosition(0,1/(double)12);
mainSplit.setDividerPosition(1,11/(double)12);
SplitPane root = new SplitPane();
root.setOrientation(Orientation.VERTICAL);
root.getItems().addAll(mainSplit, artsBox);
root.setDividerPosition(0,0.9);
root.setPrefWidth(1300);
root.setPrefHeight(750);
//Start up scene and stage
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setMaximized(true);
primaryStage.show();
}

How to Achieve One Menubar for more then one scenes in javaFx

I am basically new to Java FX 2.
Scenario:
I have 3 Scenes and I want a way to add menu-bar such that I don't i don't want to explicitly remove the menu bar from previous scene and add it to new one. Like Some thing a Parent Scene or some way menu-bar is attached to Stage. I mean menu-bar is added just one time and always be present whatever scene is in front or not.
If This is Possible How Can I do this.
Here is the Default Example Provided by Oracle Docs of JavaFX http://docs.oracle.com/javafx/2/ui_controls/MenuSample.java.html
public class Main extends Application {
final ImageView pic = new ImageView();
final Label name = new Label();
final Label binName = new Label();
final Label description = new Label();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
stage.setTitle("Menu Sample");
Scene scene = new Scene(new VBox(), 400, 350);
scene.setFill(Color.OLDLACE);
MenuBar menuBar = new MenuBar();
// --- Graphical elements
final VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.setPadding(new Insets(0, 10, 0, 10));
makeContentsForVBox();// in this vBox area will be fill with name pic desrciption
vbox.getChildren().addAll(name, binName, pic, description); // name is lable
// --- Menu File
Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Shuffle",
new ImageView(new Image(getClass().getResourceAsStream("new.png"))));
add.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
shuffle();
vbox.setVisible(true);
}
});
MenuItem clear = new MenuItem("Clear");
clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
clear.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
vbox.setVisible(false);
}
});
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);
((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
stage.setScene(scene);
stage.show();
}
}
So Here menuBar is added to a scene. if i swap the scene and bring an other scene in front ... What will i do. i think I remove menuBar from this scene and add to other or simply add to new one. so every time i have to do this when i change. Is there any way to avoid this??
The approach I would prefer is to use a Scene with BorderPane as its root
scene.setRoot(borderPane);
You can add the MenuBar to the top of the BorderPane and at its Center you can place SplitPane
BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);
borderPane.setCenter(splitPane);
Whenever you need to switch to WebView just replace it with SplitPane :
borderPane.setCenter(webView);
Following this approach, your MenuBar will always remain on TOP and you can switch between SplitPane and WebView

Categories

Resources