i want to design a GUI that contains BorderPane in the top of the container there is a MenuBar, in the left of the container there is a Acordion with different buttons that change the content of the center of the container for diferent FXML files, someting like the desktop app of Spotiffy
i got a working prototipe and it looks like this
the change in FXML happens and the buttos respont very well, the problem i have is that the FXML that fill the center part of the BoderPane doesn't auto rize and if is to big parts of the FXML doesn't show and if the FXML is smaller that the space left for the center part stays of the same small size and left alot of space with nothing
this is my code for the calling of the new FXML
public void lanzaUno(){
try {
// load first FXML
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Coordinador.class.getResource(
"VistaControlador/Usuario/Uno.fxml"));
/*i put the AnchorPane inside of a
ScrollPane for the desire funcionality of alot
of vertical space for many nodes in a single FXML file
*/
ScrollPane unoAnchorPane = (ScrollPane) loader.load();
UnoController controller = loader.getController();
//example method for passing variables to the FXML controler
controller.pasoPrincipal(this, primaryStage, "Rhutt");
//puts the FXML in the center of the BorderPane
rootLayout.setCenter(unoAnchorPane);
//this if for trying to accommodate the content en the BorderPane
BorderPane.setAlignment(unoAnchorPane, Pos.TOP_LEFT);
} catch (IOException e) {
e.printStackTrace();
}
}
my first cuestion is what is the thing i am missing in the calling of the FXML for the contents of this ocupy the space available in the BorderPane?
my secon cuestion regards the change of FXML, when i pass fron one to another the change in the BorderPane is in a instant and looks very bad is there a way for making the transicion like one where the content of a FXML that is call push the content of the FXML in the center?, it doesn't have to be very elaborated just make the transition a little better
EDIT
i got a cordinator class where i send and recive parameters for all the FXML and where i declare the methods of calling new FXML, so i have a cordinator class, a FXML root with its controller and two FXML and its controllers with different things in each one, this two FXML are the ones that change in the BorderPane center of the root
this is the coordinator class
//Variables
private Stage primaryStage;
private BorderPane rootLayout;
/**
* launh
* #param primaryStage
*
*/
#Override
public void start(Stage primaryStage) throws Exception{
// Inicializa la escena
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Login");
this.primaryStage.centerOnScreen();
//star method
iniLogin();
}
/**
*load the root scene
*/
public void iniLogin(){
try {
// Carga el loader.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(com.aohys.rehabSys.MVC.Coordinador.class.getResource(
"VistaControlador/Pricipal/Principal.fxml"));
rootLayout = (BorderPane) loader.load();
//the root scene
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// Da acceso al programa principal.
PrincipalController controller = loader.getController();
controller.pasoPrincipal(this, primaryStage);
primaryStage.centerOnScreen();
// Muesta la escena,
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
after this method there are two identical methods like the one at the beginning where i call the 2 changing FXML call LanzaUno, LanzaDos
this is my rood FXML controler
public class PrincipalController implements Initializable {
//variable of the coordinator class
private Coordinador cordi;
private Stage stage;
/**
* method for passing parameters to the FXML
* #param cordi
* #param stage
*/
public void pasoPrincipal(Coordinador cordi, Stage stage) {
this.cordi = cordi;
this.stage = stage;
}
//FXML in root
#FXML private Button btt1;
#FXML private Button btt2;
#FXML public static StackPane stackPane;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
//Call the firts FXML
btt1.setOnAction((evento)->{
cordi.lanzaUno();
});
//Call the second FXML
btt2.setOnAction((evento)->{
cordi.lanzaDos();
});
}
for the moment the controllers on the two FXML dont do anything
You should read up on Adam Bien's AfterburnerFX library for managing dependency injection and controllers in your application. It has changed my life. :)
For transitions, I use this code. It is a nice fade-out/fade-in from one screen to the next. In this case, stackPane is a StackPane in the center of your BorderPane defined in your FXML.
Here is a simple FXML with the aforementioned stackPane:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:id="borderPane" minHeight="-Infinity" minWidth="-Infinity" prefHeight="768.0" prefWidth="1280.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.tada.gui.tada.TadaPresenter">
<center>
<StackPane fx:id="stackPane" minHeight="-Infinity" minWidth="-Infinity" prefHeight="240.0" prefWidth="320.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
And the setScreen method that changes to the new one passed in:
/**
* Set Screen
*
* #param view
* #return boolean
*/
public boolean setScreen(Parent view) {
final DoubleProperty opacity = stackPane.opacityProperty();
if (!stackPane.getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(TRANSITION_TIMER), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
stackPane.getChildren().remove(0); //remove the displayed screen
stackPane.getChildren().add(0, view); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(TRANSITION_TIMER), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
stackPane.setOpacity(0.0);
stackPane.getChildren().add(view); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(TRANSITION_TIMER), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
}
You'll also need this in your controller...
private static final double TRANSITION_TIMER = 200;
EDIT:
I tried to put together a very basic "application". It is rudimentary, but I think it does a good job of illustrating the use of AfterburnerFX and the screen fade transition. There is a lot more to AfterburnerFX. I just used the view switching without the dependency injection, which is very important when you start wanting to work on objects in your application. Also, property binding is very important for a good UX. Anyway, Here is a link to my example on GitHub.
Related
I'm just a complete beginner when it comes to programming or java.
So for the start my plan was to create a window useing JavaFX(combined with scene builder) where I do have a button that leads me to another window where i do have a combobox. I googled for hours now to find a way to fill that combobox with choices but all the solutions i found don't work for me. Thats why I think I made some mistakes here and I hope you can somehow help me. Or at list give me a hint what I should learn/read to get to the solution myself.
So to start with, here's my main.java code where I build my first stage.
main.java:
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root= FXMLLoader.load(getClass().getResource("Scene-Hauptmenu.fxml"));
primaryStage.setTitle("Fishbase");
primaryStage.sizeToScene();
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(root));
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
In my "Scene-Hauptmenu.fxml" all that matters is the button that leads me to my second window:
Scene-Hauptmenu.fxml:
<Button id="btn_gefangen" fx:id="btn_gefangen" mnemonicParsing="false" onAction="#gefangen" text="Ich habe Fische gefangen!" GridPane.rowIndex="1" />
So far everything works fine and I can switch to my second window without a problem. But I think my main problem lies within my controller class so here it is.
MyController.java:
public class MyController implements Initializable{
private Node node;
private Stage stage;
private Scene scene;
private FXMLLoader fxmlLoader;
private Parent root;
#FXML
private Button btn_gefangen;
#FXML
private ComboBox<String> chobo_fisch;
#FXML
private Button btn_gefangen_zurueck;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void gefangen(ActionEvent event) throws IOException{
node = (Node) event.getSource();
stage = (Stage) node.getScene().getWindow();
scene = stage.getScene();
fxmlLoader = new FXMLLoader (getClass().getResource("gefangen.fxml"));
root = (Parent) fxmlLoader.load();
scene.setRoot(root);
stage.sizeToScene();
stage.setTitle("Fische eintragen");
}
public void gefangen_zurueck(ActionEvent event) throws IOException{
node = (Node) event.getSource();
stage = (Stage) node.getScene().getWindow();
scene = stage.getScene();
fxmlLoader = new FXMLLoader (getClass().getResource("Scene-Hauptmenu.fxml"));
root = (Parent) fxmlLoader.load();
scene.setRoot(root);
stage.sizeToScene();
stage.setTitle("Fishbase");
}
}
So the button "btn_gefangen" leads me to that other window where i do have the combobox with the fx:id "chobo_fisch".
gefangen.fxml:
<ComboBox fx:id="chobo_Fisch" prefWidth="150.0"/>
So I googled for hours but I still didnt find any solution to fill the combobox with choices that works with my code. What did I do wrong? Can anyone help me here?
Best regards
Jannik
I found three variants, depending on your setup:
1st variant
// Weekdays
String week_days[] =
{ "Monday", "Tuesday", "Wednesday",
"Thrusday", "Friday" };
// Create a combo box
ComboBox combo_box = new ComboBox(FXCollections.observableArrayList(week_days));
(Soure: https://www.geeksforgeeks.org/javafx-combobox-with-examples/)
2nd variant
final ComboBox emailComboBox = new ComboBox();
emailComboBox.getItems().addAll(
"jacob.smith#example.com",
"isabella.johnson#example.com",
"ethan.williams#example.com",
"emma.jones#example.com",
"michael.brown#example.com"
);
Source: (https://docs.oracle.com/javafx/2/ui_controls/combo-box.htm)
3rd variant (for FXML)
<ComboBox fx:id="someName">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="1"/>
<String fx:value="2"/>
<String fx:value="3"/>
<String fx:value="4"/>
</FXCollections>
</items>
<value>
<String fx:value="1"/>
</value>
</ComboBox>
Edit
As mentioned by fabian you should make sure to include the FXML imports:
<?import javafx.collections.FXCollections?>
<?import java.lang.String?>
The second one may not be needed.
I'm new to those stuff but I think this is how it should look or at least close too if I understood what you wanted.
Example below:
ComboBox<String> stuff = new ComboBox<>();
stuff.getItems().addAll("1","2","5","10");
Note: I'm new to stackoverflow.
Try this:
ObservableList<String> items = FXCollections.observableArrayList();
items.add("a");
items.add("b");
chobo_fisch.getItems().addAll(items);
Your combobox must be filled with items (in your case String):
List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
chobo_fisch.setItems(FXCollections.observableArrayList(list));
If you use a combobox of a more complex object, you could use a cellfactory to choose the value that is displayed :
chobo_fisch.setCellFactory(obj -> new ChoboFischListCell());
chobo_fisch.setButtonCell(new ChoboFischListCell());
where ChoboFischListCell is a class that extends ListCell and where you implement which field of your object should be displayed.
The best article I found was: How to create multiple javafx controllers with different fxml files?
However im really confused on how this works. All examples just seem a bit too complex for the initial learning.
So here I have a simple helloWorld for testing purposes. As you can see in the xml, I have a container, menu and footer. However, I want all 3 of them to have seperate controllers and XML files which are then merged and shown as seen in the XML below after the class:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.setLocation(getClass().getResource("main.fxml"));
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
MainController mainController = loader.getController();
}
}
XML
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.canvas.*?>
<HBox fx:id="container" id="container" fx:controller="core.GuiController" xmlns:fx="http://javafx.com/fxml">
<HBox fx:id="post" id="post">
<!-- Stuff -->
</HBox>
<HBox fx:id="friends" id="friends">
<!-- Stuff -->
</HBox>
<HBox fx:id="profile" id="profile">
<!-- Stuff -->
</HBox>
</HBox>
I could really benefit from a simple example. How can I keep them in seperate files and merge them while they each retain their own controllers?
You could follow this tutorial
public class MainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
initRootLayout();
showPersonOverview();
}
/**
* Initializes the root layout.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Shows the person overview inside the root layout.
*/
public void showPersonOverview() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
// Set person overview into the center of root layout.
rootLayout.setCenter(personOverview);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
In this example You have two fxml files, RootLayout.fxml and PersonOverview.fxml.
You set the scene of your primarystage to (BorderPane)RootLayout.fxml then add PersonOverview.fxml to the BorderPane.
i have 2 fxml
FXML A:
it contains borderpane with ID fx:id="UnitBorderPane"
FXML B:
it contains anchorpane with ID fx:id="UnitForm"
i load the "FXML B" at borderpane A on the left side
FXMLLoader loader = new
FXMLLoader(getClass().getResource("/projectname/unit/UnitForm.fxml"));
Pane pane = (Pane) loader.load();
UnitBorderPane.setLeft(pane);
it is kind of fxml form, so we have a button with action
<Button layoutX="102.0" layoutY="169.0" mnemonicParsing="false" onAction="#saveUnit" text="Save" />
how to hide that FXML A BorderPane left?
#FXML
private void saveUnit(ActionEvent event) {
BorderPane borpane = (BorderPane)UnitForm.getParent().lookup("#UnitBorderPane");
borpane.setLeft(null);
}
this code not work, the borpane variable is null so i cannot set the borderPane FXML A Left to null.
I think it should just be
BorderPane borpane = (BorderPane)UnitForm.getParent();
However, none of this feels very robust; for example if you decide to change the layout structure at all you will likely have a lot of code to change in various classes. I would add a property to the controller for UnitForm.fxml that you can observe from the controller for UnitBorderPane. Something like:
public class UnitFormController { // your actual class name may differ....
private final BooleanProperty saved = new SimpleBooleanProperty();
public BooleanProperty savedProperty() {
return saved ;
}
public final boolean isSaved() {
return savedProperty().get();
}
public final void setSaved(boolean saved) {
savedProperty().set(saved);
}
// other code as you already have...
#FXML
private void saveUnit() {
setSaved(true);
}
// ...
}
Then you do
FXMLLoader loader =
new FXMLLoader(getClass().getResource("/projectname/unit/UnitForm.fxml"));
Pane pane = (Pane) loader.load();
UnitFormController controller = loader.getController();
controller.savedProperty().addListener((obs, wasSaved, isNowSaved) -> {
if (isNowSaved) {
UnitBorderPane.setLeft(null);
}
});
UnitBorderPane.setLeft(pane);
Now the management of the UnitBorderPane is all in one place, instead of being split over two controllers, and there are no lookups (which are not robust). The controller for the UnitForm just sets a property and lets the other controller respond as it sees fit.
I'm having trouble when trying to switch from a scene to another scene. The scenario is this:
Current View and Controller: login.fxml and LoginController
Next step View and Controller: loggedWindow.fxml and UserPanelController.
Now, I'm in LoginController and trying to switch the scene to loggedWindow.fxml sending to UserPanelController a parameter, but when I'm using my code I get:
javafx.scene.layout.Pane cannot be cast to javafx.fxml.FXMLLoader
LoginController:
FXMLLoader loggedWindow = null;
loggedWindow = FXMLLoader.load(getClass().getResource("loggedWindow.fxml")); // here crashes!
Pane root = loggedWindow.load();
UserPanelController controller = loggedWindow.getController();
controller.initData(customer);
Stage switchScene = (Stage)((Node)event.getSource()).getScene().getWindow();
switchScene.setResizable(false);
switchScene.setTitle("Welcome " + customer.FirstName + " " + customer.LastName);
switchScene.setScene(new Scene(root, 800, 500));
switchScene.show();
LoggedWindow.fxml
<Pane maxHeight="500.0" maxWidth="800.0" minHeight="500.0" minWidth="800.0" prefHeight="500.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Main.UserPanelController">
<children>
<ToolBar prefHeight="40.0" prefWidth="831.0">
<items>
.
.
stuff (buttons/labels and so on).
.
.
</Pane>
I would appreciate any help! Thanks in advance.
Update 1
Also took in consideration this reference: Accessing FXML controller class
You're using the "load" method of FXMLLoader which returns the root node of your .fxml file. In that case, it's returning your Pane.
You should use it to create your scene!
See the example given in the JavaFX tutorial, like:
Pane root = FXMLLoader.load(getClass().getResource("loggedWindow.fxml"));
Scene scene = new Scene(root, width, height, color);
Other way, taken from one of my old code, using non-static FXMLLoader:
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFile));
Parent root;
try {
root = loader.load();
} catch (IOException ioe) {
// log exception
return;
}
// Color.TRANSPARENT allows use of rgba colors (alpha layer)
setScene(new Scene(root, Color.TRANSPARENT));
I'm new to Java FX and am creating an application for fun. I'm trying to add a TitledPane dynamically and am getting Null Pointer Exceptions when attempting to lookup the title of the TitledPane about 70% of the time. I tried to create a simple demo of my issue, but was unable to reproduce the issue outside of my application, but I could solve my issue. I'm hoping someone could help me understand why my solution works and maybe point me in the direction of a better solution. I'm using an FXML file with a Controller. I'm attempting to lookup the title inside of Platform.runLater() because I'm manually editing the layout and elements of the title. Inside of the Controller's initialize function, I do the following to get null pointer exceptions:
Platform.runLater(new Runnable() {
#Override
public void run() {
titledpane.lookup(".title"); // will return null about 70% of the time
}
});
// Do more stuff
However, if I wrap that call in a timer and execute it in 500 ms, it doesn't seem to ever return Null.
new java.util.Timer().schedule(new java.util.TimerTask() {
#Override
public void run() {
Platform.runLater(new Runnable() {
#Override
public void run() {
titledpane.lookup(".title"); // doesn't seem to return null
}
});
}
}, 500);
One forum mentioned that CSS had to be applied to the element prior to calling a lookup on the title, so I tried manually applying CSS to the title, but titledpane.lookup(".title") still returned null. Can anyone help me understand what is happening here? Thanks in advance!
I had the same issue. I resolved it by calling applyCss() and layout() on the pane that contains the TitledPane:
Node loadedPane = paneLoader.load();
bodyPane.setCenter(loadedPane);
bodyPane.applyCss();
bodyPane.layout();
You should read the article Creating a Custom Control with FXML.
Here's an example about how you can load a TitledPane dynamically. A TitledPane is added each time you click the "Add Task" button.
Task.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<fx:root collapsible="false" prefHeight="72.0" prefWidth="202.0" text="Task" type="TitledPane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<content>
<Pane prefHeight="43.0" prefWidth="200.0">
<children>
</children>
</Pane>
</content>
</fx:root>
Task.java
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.Region;
public class Task extends Region {
TitledPane titledPane;
public Task( String title) {
final FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "Task.fxml"));
titledPane = new TitledPane();
fxmlLoader.setRoot( titledPane);
fxmlLoader.setController( this);
try {
fxmlLoader.load();
} catch( IOException exception) {
throw new RuntimeException( exception);
}
titledPane.setText(title);
getChildren().add( titledPane);
}
}
Demo.java
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class Demo extends Application {
#Override
public void start(Stage primaryStage) {
Group root = new Group();
Button addTaskButton = new Button( "Add Task");
addTaskButton.setOnAction(new EventHandler<ActionEvent>() {
double x=0;
double y=0;
int count=0;
#Override
public void handle(ActionEvent event) {
// calculate new position
x+=50;
y+=50;
// task counter
count++;
Task task = new Task( "Task " + count);
task.relocate(x, y);
root.getChildren().add( task);
}
});
root.getChildren().add( addTaskButton);
Scene scene = new Scene( root, 1024, 768);
primaryStage.setScene( scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Screenshot:
There are various solutions in order to create a custom title. Here's one. Note: You need to provide an icon in the proper path or adapt the path. Alternatively you can just disable the ImageView node and instead use the Rectangle for demonstration purposes. It's just another node that's displayed.
public class Task extends Region {
TitledPane titledPane;
public Task( String title) {
final FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "Task.fxml"));
titledPane = new TitledPane();
fxmlLoader.setRoot( titledPane);
fxmlLoader.setController( this);
try {
fxmlLoader.load();
} catch( IOException exception) {
throw new RuntimeException( exception);
}
// create custom title with text left and icon right
AnchorPane anchorpane = new AnchorPane();
double offsetRight = 20; // just an arbitrary value. usually the offset from the left of the title
anchorpane.prefWidthProperty().bind(titledPane.widthProperty().subtract( offsetRight));
// create text for title
Label label = new Label( title);
// create icon for title
Image image = new Image( getClass().getResource( "title.png").toExternalForm());
ImageView icon = new ImageView();
icon.setImage(image);
// Rectangle icon = new Rectangle(16, 16);
// set text and icon positions
AnchorPane.setLeftAnchor(label, 0.0);
AnchorPane.setRightAnchor(icon, 0.0);
// add text and icon to custom title
anchorpane.getChildren().addAll( label, icon);
// set custom title
titledPane.setGraphic( anchorpane);
// show only our custom title, don't show the text of titlePane
titledPane.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
getChildren().add( titledPane);
}
}