Is there a way to call the event handler method from the fxml file which holds parameter? please find the files:
My Fxml Looks like:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.cognizant.iotworkbench.View.AddImageController">
<children>
<Label layoutX="270.0" layoutY="14.0" text="Add Sensor" />
<BorderPane layoutY="-1.0" prefHeight="400.0" prefWidth="602.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<left>
<HBox fx:id="source" prefHeight="100.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<ImageView fx:id="sourceimg" fitHeight="114.0" fitWidth="142.0" onDragDetected="#setUpGestureSource" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="file:Images/Project.png" />
</image>
</ImageView>
</children>
</HBox>
</left>
<right>
<HBox fx:id="target" onDragDropped="#setUpGestureTarget" onDragOver="#setUpGestureTarget" prefHeight="100.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</right>
</BorderPane>
</children>
</AnchorPane>
My controller class looks like
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
/**
* FXML Controller class
*
*/
public class AddImage implements Initializable,ControlledScreen {
ScreensController myController;
/**
* Initializes the controller class.
*/
#FXML
final HBox target=new HBox();
#FXML
final HBox source=new HBox();
#FXML
final ImageView sourceimg=new ImageView();
#FXML
public void setUpGestureSource()
{
System.out.println("source");
source.setOnDragDetected(new EventHandler <MouseEvent>() {
#Override
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture*/
System.out.println("onDragDetected");
/* allow MOVE transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.COPY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
Image sourceImage = sourceimg.getImage();
content.putImage(sourceImage);
db.setContent(content);
event.consume();
}
});
}
#FXML
public void setUpGestureTarget(){
System.out.println("target");
target.setOnDragOver(new EventHandler <DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if(db.hasImage()){
event.acceptTransferModes(TransferMode.COPY);
}
event.consume();
}
});
target.setOnDragDropped(new EventHandler <DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if(db.hasImage()){
insertImage(db.getImage(), target);
event.setDropCompleted(true);
}else{
event.setDropCompleted(false);
}
event.consume();
}
});
}
void insertImage(Image i, HBox hb){
ImageView iv = new ImageView();
iv.setImage(i);
setUpGestureSource();
hb.getChildren().add(iv);
}
#Override
public void setScreenParent(ScreensController screenParent) {
myController=screenParent;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Drag and Drop event is not getting fired. I dont know what's wrong with the code. Please help
All methods that are annotated with #FXML may or may not have a parameter. If you need a parameter, you can directly pass the specific Event as a parameter to the method.
Let us take an example and say you have an onDragOver event added for a HBox in the fxml.
<HBox fx:id="targetBox" onDragOver="#setupGestureTarget">
...
</HBox>
Then you may have a method which does the needful inside the controller class.
#FXML
public void setupGestureTarget(DragEvent event) {
Dragboard db = event.getDragboard();
if(db.hasImage()){
event.acceptTransferModes(TransferMode.COPY);
}
event.consume();
}
If you need the source node for which the method was called, you can get an access to it by getSource() of the event, then type-caste it to Node.
public void setupGestureTarget(DragEvent event) {
...
((Node)event.getSource()).setId("myHbox");
System.out.println(targetBox.getId()); // Prints - myHbox
}
Note : For using methods specific to HBox, you can type-caste it to a HBox instead of a Node.
EDIT - As per user comments and updates
There are multiple issues with your approach. Let me address them all.
1.Values to the fields annotated with #FXML are injected while the FXML is getting loaded and should not carry new keyword.
#FXML
final HBox target=new HBox();
should be replaced by
#FXML
final HBox target;
2.As I have already stated your method can have a parameter which defines the Event. So the methods setUpGestureSource() and setUpGestureTarget() can be defined as :
#FXML
public void setUpGestureSource(DragEvent event) {
...
}
#FXML
public void setUpGestureTarget(DragEvent event) {
...
}
3.The method setUpGestureSource is called when a drag-event occurs on the ImageView, so you don't need to add another EventHandler for it.
#FXML
public void setUpGestureSource(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture*/
System.out.println("onDragDetected");
* allow MOVE transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.COPY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
Image sourceImage = sourceimg.getImage();
content.putImage(sourceImage);
db.setContent(content);
event.consume();
}
Similarly, change the other method as well.
Related
I would like to change the MenuItem's text to bold when the user clicks on it. To manage to do this I'm using setStyle, but unfortunately it has no visible effect. The css makes no effect when the user selects the MenuItem option. The css styling only has an effect in initialize method.
I created a minimal reproducible example for the problem:
MAIN:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public final class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("MainView.fxml"));
Scene scene = new Scene(root, 850.0, 650.0);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
MAIN FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane prefHeight="475.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="MainController">
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu fx:id="menu" mnemonicParsing="false" text="Switch Chart">
<items>
<MenuItem text="MenuItem1" />
<MenuItem onAction="#setFontBold" text="MenuItem2" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
</BorderPane>
MAIN CONTROLLER:
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
public class MainController implements Initializable {
#FXML private Menu menu;
private List<MenuItem> menuItems;
#Override
public void initialize(URL location, ResourceBundle resources) {
menuItems = menu.getItems();
menuItems.get(0).setStyle("-fx-font-weight: bold");
}
public void setFontBold() {
menuItems.get(1).setStyle("-fx-font-weight: bold");
System.out.println(menuItems.get(1).getStyle());
System.out.println("Font set to bold in menuitem with index 1 has no effect...");
}
}
So I get the following css effects, even after selecting the first indexed menu item (so onAction=#setFontBold not changes anything visually).
No bold effect. - only if you set the style in initialize()
I'm curious about why it makes no difference? It definitely sets the style to bold, but it is displayed as a regular font even after changing it to bold.
EDIT: JavaFX version: 8.0.211-b10
If I would have to stick to javafx 8 and switching was the requirement, I would have used RadioMenuItem. It does the job as expected, but does not make MenuItem text bold.
From official docs, I found following excerpt that would be useful.
ToggleGroup toggleGroup = new ToggleGroup();
RadioMenuItem radioItem1 = new RadioMenuItem("Option 1");
radioItem.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
System.out.println("radio toggled");
}
});
radioItem1.setToggleGroup(toggleGroup);
RadioMenuItem radioItem2 = new RadioMenuItem("Option 2");
radioItem.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
System.out.println("radio toggled");
}
});
radioItem2.setToggleGroup(toggleGroup);
I have strange problem while dragging selected text from TextArea. The text is properly selected but when iam dragging to be place on the target position, the selection of text is changed, it reduce the selection for 2-3 characters randomly.
Here is the complete class :
public class DnDMainController extends Application {
ClipboardContent cb = new ClipboardContent();
ObservableList<String> list = FXCollections.observableArrayList();
#FXML
private TextArea sourceText;
#FXML
private ListView<String> listView;
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/main/DnD.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Simple Drag and Drop ExampleGame");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
#FXML
void _detectDrag(MouseEvent event) {
Dragboard db = sourceText.startDragAndDrop(TransferMode.COPY);
cb.putString(sourceText.getSelectedText());
db.setContent(cb);
event.consume();
}
#FXML
void _dragExited(DragEvent event) {
String st = event.getDragboard().getString();
if (!(list.contains(st.trim()))) {
list.add(st);
listView.getItems().addAll(list);
}}
}
[![gif for DnD Issue][1]][1]
I have tried the same on TextField and it is working perfectly on TextField. But unfortunatelly i can not use the TextField due to large string of text. I dont know what Iam doing wrong...
FXML CODE:
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="549.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="main.DnDMainController">
<children>
<TextArea fx:id="sourceText" layoutY="273.0" onDragDetected="#_detectDrag" prefHeight="127.0" prefWidth="550.0" text="There was once a velveteen rabbit, and in the beginning he was really splendid. He was fat and bunchy, as a rabbit should be; his coat was spotted brown and white, he had real thread whiskers, and his ears were lined with pink sateen. On Christmas morning, when he sat wedged in the top of the Boy’s stocking, with a sprig of holly between his paws, the effect was charming." wrapText="true">
<font>
<Font size="19.0" />
</font></TextArea>
<ListView fx:id="listView" layoutY="40.0" onDragExited="#_dragExited" onMouseClicked="#_callContext" prefHeight="200.0" prefWidth="516.0" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="-2.0" layoutY="2.0" prefHeight="38.0" prefWidth="550.0" text="List of Words" textAlignment="CENTER" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="7.0" layoutY="240.0" prefHeight="32.0" prefWidth="542.0" text="Story" textAlignment="CENTER" />
</children>
</AnchorPane>```
I ran into a few problems trying to implement this in a straightforward way. I had to create a toggle that would allow me to select text and then drag the text. During the drag, I noticed that it would not grab all of the selected text unless the drag was started at the end of the selected text. I fixed that by grabbing the selected text after it was selected and the toggle mode is changed to drag mode. MCVE below.
Main
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.Parent;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Test.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Simple Drag and Drop ExampleGame");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToggleButton?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="583.0" prefWidth="851.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javaapplication12.TestController">
<children>
<ListView fx:id="listView" layoutX="326.0" layoutY="14.0" onDragDropped="#dragDropped" onDragEntered="#dragEntered" onDragOver="#dragOver" prefHeight="200.0" prefWidth="200.0" />
<TextArea fx:id="textArea" layoutX="224.0" layoutY="274.0" onDragDetected="#dragDetected" prefHeight="247.0" prefWidth="426.0" text="There was once a velveteen rabbit, and in the beginning he was really splendid. He was fat and bunchy, as a rabbit should be; his coat was spotted brown and white, he had real thread whiskers, and his ears were lined with pink sateen. On Christmas morning, when he sat wedged in the top of the Boy’s stocking, with a sprig of holly between his paws, the effect was charming." wrapText="true" />
<ToggleButton fx:id="tbtnDragMode" layoutX="44.0" layoutY="26.0" mnemonicParsing="false" onAction="#handleTbtnDragMode" text="Select Text Mode" />
</children>
</AnchorPane>
Controller
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleButton;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
public class TestController implements Initializable {
#FXML TextArea textArea;
#FXML ListView listView;
#FXML ToggleButton tbtnDragMode;
ObservableList<String> list = FXCollections.observableArrayList();
String selectedText = "";
#Override
public void initialize(URL url, ResourceBundle rb) {
listView.setItems(list);
list.add("test");
}
#FXML private void handleTbtnDragMode(ActionEvent actionEvent)
{
if(tbtnDragMode.isSelected())
{
System.out.println("Drag Mode On");
tbtnDragMode.setText("Drag Mode");
selectedText = textArea.getSelectedText().isBlank() ? "" : textArea.getSelectedText();
}
else {
System.out.println("Drag Mode Off");
tbtnDragMode.setText("Select Text Mode");
}
}
#FXML
private void dragDetected(MouseEvent event) {
System.out.println("drag detected 1");
System.out.println(tbtnDragMode.isSelected());
if(tbtnDragMode.isSelected())
{
System.out.println("drag detected 2");
/* drag was detected, start a drag-and-drop gesture*/
/* allow any transfer mode */
Dragboard db = textArea.startDragAndDrop(TransferMode.ANY);
/* Put a string on a dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(selectedText);
db.setContent(content);
event.consume();
}
}
#FXML
private void dragEntered(DragEvent event) {
System.out.println("dragEntered");
event.consume();
}
#FXML
private void dragDropped(DragEvent event)
{
System.out.println("Drag dropped");
/* data dropped */
/* if there is a string data on dragboard, read it and use it */
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
list.add(db.getString());
success = true;
}
/* let the source know whether the string was successfully
* transferred and used */
event.setDropCompleted(success);
event.consume();
}
#FXML
private void dragDone(DragEvent event) {
/* the drag and drop gesture ended */
/* if the data was successfully moved, clear it */
System.out.println("drag done");
if (event.getTransferMode() == TransferMode.MOVE) {
//clear textarea selection
System.out.println("drag done");
}
event.consume();
}
#FXML
private void dragExited(DragEvent event) {
System.out.println("dragExited");
event.consume();
}
#FXML
private void dragOver(DragEvent event) {
/* data is dragged over the target */
/* accept it only if it is not dragged from the same node
* and if it has a string data */
System.out.println(event.getGestureSource() + " - " + event.getTarget());
if (event.getGestureSource() != event.getTarget() &&
event.getDragboard().hasString()) {
/* allow for both copying and moving, whatever user chooses */
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
}
I've seen bunch of posts connected with my problem but it seems like nothing works for me. I'm writing simple window app in Java FX and FXML. I have a Main class which has field with days names. I've got also two controller classes - Controller (which is like more important controller) and ShowDays. Each controller has their own FXML and they are responsible for switching scenes and working with user (and with Model = Main). In Controller class user can add a new day to our days names or remove last day. In ShowDays class user can print on window names of days. It's all connected with clicking buttons.
I know that I can organize my program easier and I can print names of days in Controller class and remove all ShowDays class but it's only a part of project I want to create and I just want to understand how real programmers would have done this kind of things.
This is my code:
public class Main extends Application {
private ArrayList<String> daysNames;
public Main() {
daysNames = new ArrayList<>();
}
public void addDay() {
String[] days = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
System.out.println("I'm adding day!" + daysNames.size());
if (getDaysNames().size() < 7)
getDaysNames().add(days[getDaysNames().size()]);
else
System.out.println("Can't add more days!");
}
public void removeDay() {
if (!getDaysNames().isEmpty())
getDaysNames().remove(getDaysNames().get(getDaysNames().size()-1));
}
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
//setters,getters...
}
Controller class:
public class Controller implements Initializable {
private Main myMain;
#FXML
private ShowDays showDays;
public Controller() {
myMain=new Main();
showDays = new ShowDays(myMain);
}
public Controller(Main main) {
this.myMain = main;
showDays = new ShowDays(myMain);
}
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void addDay() {
myMain.addDay();
}
public void removeDay() {
myMain.removeDay();
}
public void GOTOshowDays(ActionEvent event) throws IOException {
Parent showDaysParent = FXMLLoader.load(getClass().getResource("ShowDays.fxml"));
Scene showDaysScene = new Scene(showDaysParent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(showDaysScene);
window.show();
}
}
ShowDays class:
public class ShowDays implements Initializable {
#FXML
private Text text;
private Main myMain;
public ShowDays() {
myMain = new Main();
}
public ShowDays(Main main) {
myMain = main;
}
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void BackToController(ActionEvent event) throws IOException {
Parent controllerParent = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene controllerScene = new Scene(controllerParent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(controllerScene);
window.show();
}
public void showDaysInWindow(ActionEvent event) throws IOException {
String allText = "";
for (String day : myMain.getDaysNames())
allText += day + " ";
text.setText(allText);
}
}
and the FXML files:
sample.fxml
<HBox prefHeight="100.0" prefWidth="483.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<children>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Button layoutX="-8.0" layoutY="48.0" mnemonicParsing="false" onAction="#GOTOshowDays" text="GOTO show days" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
<Button mnemonicParsing="false" onAction="#addDay" text="add day" />
<Button mnemonicParsing="false" onAction="#removeDay" text="remove day" />
ShowDays.fxml
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ShowDays">
<center>
<Text fx:id="text" strokeType="OUTSIDE" strokeWidth="0.0" BorderPane.alignment="CENTER" />
</center>
<top>
<Button mnemonicParsing="false" onAction="#showDaysInWindow" text="Show days" BorderPane.alignment="CENTER" />
</top>
<bottom>
<Button mnemonicParsing="false" onAction="#BackToController" text="Go back" BorderPane.alignment="CENTER" />
</bottom>
</BorderPane>
I'm not sure if ShowDays user actions works as expected (it's all about that...) but Controller do. The problem is when I add a few days in Controller scene and then switch scene to ShowDays scene, it seems like I lose my Main instance... When I have one controller class, my code cope with working all time on the same instance of Main and adding/removing days works as expected but I can't cope with connecting multiple controllers to model and them each other... I've spend so much time trying to fix this and I don't really understand all of the tips which I found on the internet, so I ask you.
You should use Ideas from #James_D answer here. Your problem is how to pass a model from one Controller to the next. In this example, the model is a List<String>. The model is passed to the initial Controller named FXMLDocumentController. From that point, the model is passed between FXMLDocumentController and ShowDayscontroller. The showDaysInWindow method, shows the current model info in a Text node. addDay adds a day from the array days if the model is missing a day. removeDay removes a day from the model.
Main
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication320 extends Application
{
#Override
public void start(Stage stage)
{
try {
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
List<String> daysNames = new ArrayList();
for (int i = 0; i < days.length; i++) {
daysNames.add(days[i]);
}
//Load the FXML. Pass the model to initModel
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
loader.load();
FXMLDocumentController fXMLDocumentController = loader.getController();
fXMLDocumentController.initModel(daysNames);
Scene scene = new Scene(loader.getRoot());
stage.setScene(scene);
stage.show();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
FXMLDocumentController
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class FXMLDocumentController implements Initializable
{
List<String> model;
#FXML
private void goToShowDays(ActionEvent event)
{
try {
FXMLLoader showDaysLoader = new FXMLLoader(getClass().getResource("ShowDays.fxml"));
showDaysLoader.load();
ShowDaysController showDaysController = showDaysLoader.getController();
showDaysController.initModel(this.model);
Stage stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
stage.setScene(new Scene(showDaysLoader.getRoot()));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
#FXML
private void addDay(ActionEvent event)
{
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
List<String> tempDays = new ArrayList(Arrays.asList(days));
if (!this.model.containsAll(tempDays)) {
tempDays.removeAll(this.model);
if (tempDays.size() > 0) {
this.model.add(tempDays.get(0));
}
}
}
#FXML
private void removeDay(ActionEvent event)
{
if (this.model.size() > 0) {
Random random = new Random();
this.model.remove(random.nextInt(this.model.size()));
}
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO
}
public void initModel(List<String> model)
{
// ensure model is only set once:
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
this.model = model;
this.model.forEach(System.out::println);
}
}
FXMLDocument
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox prefHeight="100.0" prefWidth="483.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication320.FXMLDocumentController">
<children>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<Button layoutX="-8.0" layoutY="48.0" mnemonicParsing="false" onAction="#goToShowDays" text="GOTO show days" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
<Button mnemonicParsing="false" onAction="#addDay" text="add day" />
<Button mnemonicParsing="false" onAction="#removeDay" text="remove day" />
</children>
</HBox>
ShowDaysController
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author blj0011
*/
public class ShowDaysController implements Initializable
{
#FXML
Text text;
List<String> model;
#FXML
private void showDaysInWindow(ActionEvent event)
{
text.setText(String.join(" ", this.model));
}
#FXML
private void backToController(ActionEvent event)
{
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
loader.load();
FXMLDocumentController fXMLDocumentController = loader.getController();
fXMLDocumentController.initModel(this.model);
Stage stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
stage.setScene(new Scene(loader.getRoot()));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Initializes the controller class.
*
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO
}
public void initModel(List<String> model)
{
// ensure model is only set once:
if (this.model != null) {
throw new IllegalStateException("Model can only be initialized once");
}
this.model = model;
this.model.forEach(System.out::println);
}
}
ShowDays FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication320.ShowDaysController">
<center>
<Text fx:id="text" strokeType="OUTSIDE" strokeWidth="0.0" BorderPane.alignment="CENTER" />
</center>
<top>
<Button mnemonicParsing="false" onAction="#showDaysInWindow" text="Show days" BorderPane.alignment="CENTER" />
</top>
<bottom>
<Button mnemonicParsing="false" onAction="#backToController" text="Go back" BorderPane.alignment="CENTER" />
</bottom>
</BorderPane>
I'm working on a personal weather project that contains Main.fxml, MainController.java, EnterCityDocument.fxml, and EnterCityDocumentController.java.
Main.fxml: contains a border-pane and at its center it has a ListView that displays names of cities. It also has a "Add" Button to open a new modal window(EnterCityDocument.fxml) to add a city to its ListView.
EnterCityDocument.fxml: has a listView that contains names of cities and a "Select" button to select a city the user wants to display in Main.fxml. When the user clicks the "Select" Button, the modal window (EnterCityDocument.fxml) closes and the Main.fxml continues to run.
MainController.java is the parent class of EnterCityDocumentController.java.
I've been looking for passing data from the child class(EnterCityDocumentController.java) to the parent class (MainController.java) and found a way to do it, but all of the methods i've found require to refresh the MainController.java class whenever the user selects a city in EnterCityDocumentController.java.
Is there a way to update the Main.fxml without refreshing the main scene when a new city is added into the listView of the Main.fxml?
Hope my question is clear enough. If you need a further explanation/code, please let me know!
All you need to do is arrange for the new city from the dialog to be added to the list view's backing list. Since you are using showAndWait() this is very easy: just define a method in the EnterCityDocumentController class that returns the new city, and call it after showAndWait():
public class EnterCityDocumentController {
#FXML
private TextField cityNameField ;
// other fields, etc...
#FXML
private void okButtonPressed() {
// just close the window:
cityNameField.getScene().getWindow().hide();
}
public City getUserCity() {
return new City(cityNameField.getText());
}
}
Then in the main controller:
public class MainController {
#FXML
private ListView<City> listView ;
// handler method:
#FXML
public void addNewCity() throws IOException {
FXMLLoader loader = new FXMLLoader(EnterCityDocumentController.class.getResource("EnterCityDocument.fxml"));
Scene scene = new Scene(loader.load());
Stage stage = new Stage();
stage.setScene(scene);
stage.showAndWait();
listView.getItems().add(controller.getUserCity());
}
}
Here is a SSCCE:
app/Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.BorderPane?>
<BorderPane xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="app.MainController">
<center>
<ListView fx:id="listView" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</center>
<bottom>
<Button mnemonicParsing="false" onAction="#addNewElement" text="Add..." BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
</BorderPane.margin>
</Button>
</bottom>
</BorderPane>
app/AddNewElement.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane hgap="5.0" vgap="5.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="app.AddNewElementController">
<rowConstraints>
<RowConstraints />
<RowConstraints />
</rowConstraints>
<columnConstraints>
<ColumnConstraints halignment="CENTER" />
<ColumnConstraints halignment="CENTER" />
</columnConstraints>
<children>
<TextField fx:id="textField" GridPane.columnSpan="2" />
<Button defaultButton="true" mnemonicParsing="false" onAction="#ok" text="OK" GridPane.rowIndex="1" />
<Button cancelButton="true" mnemonicParsing="false" onAction="#cancel" text="Cancel" GridPane.columnIndex="1" GridPane.rowIndex="1" />
</children>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
</padding>
</GridPane>
app/AddNewElementController.java:
package app;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class AddNewElementController {
#FXML
private TextField textField ;
private boolean approved ;
public boolean isApproved() {
return approved ;
}
public String getUserText() {
return isApproved() ? textField.getText() : null ;
}
#FXML
private void cancel() {
approved = false ;
hide();
}
#FXML
private void ok() {
approved = true ;
hide();
}
private void hide() {
textField.getScene().getWindow().hide();
}
}
app/MainController.java:
package app;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class MainController {
#FXML
private ListView<String> listView ;
#FXML
private void addNewElement() throws IOException {
FXMLLoader loader = new FXMLLoader(AddNewElementController.class.getResource("AddNewElement.fxml"));
Parent root = loader.load();
AddNewElementController controller = loader.getController();
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(listView.getScene().getWindow());
stage.setScene(scene);
stage.showAndWait();
if (controller.isApproved()) {
listView.getItems().add(controller.getUserText());
}
}
}
app/Main.java:
package app;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(MainController.class.getResource("Main.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Another, very slightly different approach, is to pass the listview's backing list to the second controller. Then the second controller can add the item directly to the list (and the list view will automatically update, as before). This approach can be used even if you are not using showAndWait() (it doesn't rely on the code blocking until the user dismisses the window).
package app;
import java.util.List;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class AddNewElementController {
#FXML
private TextField textField ;
private List<String> itemList ;
public void setItemList(List<String> itemList) {
this.itemList = itemList ;
}
#FXML
private void cancel() {
hide();
}
#FXML
private void ok() {
itemList.add(textField.getText());
hide();
}
private void hide() {
textField.getScene().getWindow().hide();
}
}
and
package app;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class MainController {
#FXML
private ListView<String> listView ;
#FXML
private void addNewElement() throws IOException {
FXMLLoader loader = new FXMLLoader(AddNewElementController.class.getResource("AddNewElement.fxml"));
Parent root = loader.load();
AddNewElementController controller = loader.getController();
controller.setItemList(listView.getItems());
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(listView.getScene().getWindow());
stage.setScene(scene);
stage.showAndWait();
}
}
I am working on a new GUI client and we are considering using JavaFX. I was wondering if anyone has a suggestion regarding making a draggable ToolWindow:
(Customer window) in the example. This mini-window should be able to get minimized and dragged out of the parent window, and docked back to it. I really do not want to use netbeans platform (or eclipse or swing for that matter).
You just have to create a custom pane for that:
The complete example is available on gist.
CustomPane.java
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
public class CustomPane extends AnchorPane implements Initializable {
#FXML Button closePane;
#FXML Button minPane;
#FXML Label title;
#FXML Pane contentPane;
#FXML Rectangle separator;
private boolean restoreFlag = false;
private double prefX;
private double prefY;
public CustomPane(String title){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(
"CustomPane.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
this.title.setText(title);
setButtonsLayout();
setStandardLayout();
}
public CustomPane(String title, double y, double x){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(
"CustomPane.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (Exception exception) {
throw new RuntimeException(exception);
}
this.title.setText(title);
this.setPrefSize(x, y);
setButtonsLayout();
setStandardLayout();
restoreRoot();
}
#Override
public void initialize(URL location, ResourceBundle resources) {
closePane.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
setInvisible();
}
});
minPane.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
if(restoreFlag){
restoreFlag = false;
minPane.setText("_");
restoreRoot();
}
else{
restoreFlag = true;
minPane.setText("▭");
minimizeRoot();
}
}
});
}
protected void minimizeRoot() {
this.setPrefSize(prefX/2, title.getPrefHeight() + 5.0);
separator.setWidth(prefX/2 + 5);
this.setLayoutX(0);
this.setLayoutY(prefY-40);
setButtonsLayout();
contentPane.setVisible(false);
}
protected void restoreRoot() {
this.setPrefSize(prefX, prefY);
separator.setWidth(prefX);
contentPane.setVisible(true);
this.setLayoutX(0);
this.setLayoutY(0);
setButtonsLayout();
}
private void setStandardLayout() {
prefX = this.getPrefHeight();
prefY = this.getPrefWidth()-50;
}
public void setButtonsLayout(){
closePane.setLayoutX(this.getPrefWidth()-30);
minPane.setLayoutX(this.getPrefWidth()-55);
}
public void setInvisible(){
this.setVisible(false);
}
public ObservableList<Node> getContent(){
return contentPane.getChildren();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
customPane.fxml
<fx:root prefHeight="400.0" prefWidth="400.0"
type="javafx.scene.layout.AnchorPane" xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1">
<children>
<Rectangle fx:id="separator" arcHeight="5.0" arcWidth="5.0" fill="WHITE"
height="33.0" layoutY="1.0" stroke="BLACK" strokeType="INSIDE" width="600.0" />
<Button fx:id="closePane" layoutX="573.0" layoutY="6.0"
mnemonicParsing="false" text="X" />
<Button fx:id="minPane" layoutX="545.0" layoutY="6.0"
mnemonicParsing="false" text="__" />
<Label fx:id="title" layoutX="14.0" layoutY="12.0" text="Title" />
<Pane fx:id="contentPane" layoutY="34.0" prefHeight="366.0"
prefWidth="600.0" />
</children>
</fx:root>