Minimal classes to reproduce the issue:
import static com.gluonhq.charm.glisten.application.AppManager.*;
import javafx.application.Application;
import javafx.stage.Stage;
import com.gluonhq.charm.glisten.application.AppManager;
import com.gpsdemo.view.View1;
import com.gpsdemo.view.View2;
public class MyApplication extends Application {
AppManager appManager = AppManager.initialize();
public static final String VIEW1 = HOME_VIEW;
public static final String VIEW2 = "View2";
#Override
public void init() {
appManager.addViewFactory(VIEW1, View1::get);
appManager.addViewFactory(VIEW2, View2::get);
}
#Override
public void start(Stage stage) throws Exception {
appManager.start(stage);
if (com.gluonhq.attach.util.Platform.isDesktop()) {
stage.setHeight(600);
stage.setWidth(360);
stage.centerOnScreen();
}
}
public static void main(String args[]) {
launch(args);
}
}
import javafx.scene.control.Label;
import com.gluonhq.charm.glisten.control.AppBar;
import com.gluonhq.charm.glisten.mvc.View;
import com.gluonhq.charm.glisten.visual.MaterialDesignIcon;
import com.gpsdemo.MyApplication;
public class View1 extends View {
private static View1 INSTANCE;
public static View1 get() {
return INSTANCE != null ? INSTANCE : (INSTANCE = new View1());
}
private View1() {
setCenter(new Label("Nothing to see here"));
}
#Override
protected void updateAppBar(AppBar appBar) {
appBar.setTitleText("View1");
var optionsButton = MaterialDesignIcon.MENU.button(e -> getAppManager().switchView(MyApplication.VIEW2));
appBar.getActionItems().add(optionsButton);
}
}
import java.util.Set;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Node;
import com.gluonhq.charm.glisten.control.AppBar;
import com.gluonhq.charm.glisten.control.SettingsPane;
import com.gluonhq.charm.glisten.control.settings.DefaultOption;
import com.gluonhq.charm.glisten.mvc.View;
import com.gluonhq.charm.glisten.visual.MaterialDesignIcon;
public class View2 extends View {
private static View2 INSTANCE;
public static View2 get() {
return INSTANCE != null ? INSTANCE : (INSTANCE = new View2());
}
private View2() {
var settingsPane = new SettingsPane();
var option = new DefaultOption<>("Title", "Description", "Category", new SimpleDoubleProperty(), true);
settingsPane.getOptions().add(option);
setCenter(settingsPane);
setOnShown(e -> {
System.out.println("On shown");
Set<Node> lookup = settingsPane.lookupAll(".secondary-graphic");
System.out.println(lookup);
});
}
#Override
protected void updateAppBar(AppBar appBar) {
appBar.setTitleText("View2");
var backButton = MaterialDesignIcon.ARROW_BACK.button(e -> getAppManager().switchToPreviousView().get());
appBar.setNavIcon(backButton);
}
}
Launch the application normally, View1 will show.
Click on the button to show View2. The first time View2 is loaded the output is
On shown
[]
So the lookup fails in the onShown event.
Click on the back button and then show View2 again. The output is
On shown
[HBox#2c8d8a10[styleClass=secondary-graphic]]
which is correct.
If View2 is set as HOME_VIEW, the lookup will find the nodes correctly on the first onShown event. This looks like a bug to me. Regardless, I would like the lookup to succeed on the first time so I can configure the view correctly.
Using:
<javafx-maven-plugin-version>0.0.8</javafx-maven-plugin-version>
<gluonfx-maven-plugin-version>1.0.14</gluonfx-maven-plugin-version>
<java-version>17</java-version>
<javafx-version>18.0.1</javafx-version>
<charm-version>6.1.0</charm-version>
As mentioned in the comments, the issue is that the SHOWN event does not happen after a css pass is applied, therefore the lookup fails. A fix can be to manually do a css pass before the lookup, inside the SHOWN handler:
setOnShown(e -> {
System.out.println("On shown");
settingsPane.applyCss();
Set<Node> lookup = settingsPane.lookupAll(".secondary-graphic");
System.out.println(lookup);
});
This is confusing because the SHOWN event does not actually happen after the view is fully shown (in which case a css pass has happened). The event also behaves differently than JavaFX's dialog DIALOG_SHOWN event, that does happen after the dialog is fully shown (including a css pass).
Related
I want to ask if it is possible to make a chip in JFXChipView editable once it has been set.
You can create your own JFXChip and implement a behavior to enable editing. First, you need to have an editable label. I looked up online and I found this post: JavaFX custom control - editable label. Then, you can extend JFXChip to use that EditableLabel:
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXChip;
import com.jfoenix.controls.JFXChipView;
import com.jfoenix.svg.SVGGlyph;
import javafx.beans.binding.Bindings;
import javafx.beans.property.Property;
import javafx.scene.layout.HBox;
public class EditableChip<T> extends JFXChip<Property<T>> {
protected final HBox root;
public EditableChip(JFXChipView<Property<T>> view, Property<T> item) {
super(view, item);
JFXButton closeButton = new JFXButton(null, new SVGGlyph());
closeButton.getStyleClass().add("close-button");
closeButton.setOnAction(event -> {
view.getChips().remove(item);
event.consume();
});
// Create the label with an initial value from the item
String initialValue = view.getConverter().toString(item);
EditableLabel label = new EditableLabel(initialValue);
label.setMaxWidth(100);
// Bind the item to the text in the label
item.bind(Bindings.createObjectBinding(() -> view.getConverter().fromString(label.getText()).getValue(), label.textProperty()));
root = new HBox(label, closeButton);
getChildren().setAll(root);
}
}
Note: I am using Property<T> instead of using the desired class T because JFXChipView stores the item the first time you add it. And in that case, you're going to get the values as you entered them the first time when calling JFXChipView#getChips().
Sample application:
import com.jfoenix.controls.JFXChipView;
import javafx.application.Application;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class EditableChipViewApp extends Application {
#Override
public void start(Stage primaryStage) {
JFXChipView<Property<String>> chipView = new JFXChipView<>();
chipView.setChipFactory(EditableChip::new);
chipView.setConverter(new StringConverter<Property<String>>() {
#Override
public String toString(Property<String> object) {
return object == null ? null : object.getValue();
}
#Override
public Property<String> fromString(String string) {
return new SimpleStringProperty(string);
}
});
VBox container = new VBox(chipView);
Scene scene = new Scene(container, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Result:
This is how you get the actual values of the chips:
List<String> chipsValues = chipView.getChips().stream().map(Property::getValue).collect(Collectors.toList());
How can I make a custom Event that triggers on Stage.setScene()?
In my code, the button switches the Scenes and that works fine. However, I would like to extend the Stage to have an additional Event that is triggered when a button or possibly any other Element triggers a setScene.
Example:
package sample;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) {
Group g1 = new Group();
Button b1 = new Button("2");
g1.getChildren().setAll(b1);
Scene scene1 = new Scene(g1, 50, 50);
Group g2 = new Group();
Button b2 = new Button("1");
g2.getChildren().setAll(b2);
Scene scene2 = new Scene(g2, 50, 50);
stage.setScene(scene1);
stage.setTitle("JavaFX Application Life Cycle");
b1.setOnAction(actionEvent -> {
System.out.println("1");
stage.setScene(scene2);
});
b2.setOnAction(actionEvent -> {
System.out.println("2");
stage.setScene(scene1);
});
stage.show();
}
}
You can add a ChangeListener<Scene> to your Stage like this:
stage.sceneProperty().addListener((observable, oldScene, newScene) -> {
System.out.println("New scene: " + newScene);
System.out.println("Old scene: " + oldScene);
});
I believe using a listener, as shown in the answer by #M.S., is probably the best and simplest way to react to scene changes. However, you ask about how to make a "custom event" that you can fire when the scene changes; by "event" I assume you mean a subclass of javafx.event.Event. So while I recommend sticking with a simple listener, here's an example of a custom event.
First, you need a custom event class:
import javafx.event.Event;
import javafx.event.EventType;
import javafx.scene.Scene;
import javafx.stage.Window;
public class SceneChangedEvent extends Event {
public static final EventType<SceneChangedEvent> SCENE_CHANGED =
new EventType<>(Event.ANY, "SCENE_CHANGED");
public static final EventType<SceneChangedEvent> ANY = SCENE_CHANGED;
private transient Window window;
private transient Scene oldScene;
private transient Scene newScene;
public SceneChangedEvent(Window window, Scene oldScene, Scene newScene) {
super(window, window, SCENE_CHANGED);
this.window = window;
this.oldScene = oldScene;
this.newScene = newScene;
}
public Window getWindow() {
return window;
}
public Scene getOldScene() {
return oldScene;
}
public Scene getNewScene() {
return newScene;
}
}
I'm not sure what information you want to carry with the event so I just added the source Window as well as the old and new Scenes. If you're wondering about the ANY = SCENE_CHANGED, I'm just following the pattern used by javafx.event.ActionEvent (which also only has a single event-type).
Then you simply need to fire the event when the scene changes. To implement this you're still going to need a change listener. As you mention wanting to extend Stage here's an example of that:
import javafx.beans.NamedArg;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class CustomStage extends Stage {
private final ObjectProperty<EventHandler<? super SceneChangedEvent>> onSceneChanged =
new SimpleObjectProperty<>(this, "onSceneChanged") {
#Override
protected void invalidated() {
setEventHandler(SceneChangedEvent.SCENE_CHANGED, get());
}
};
public final void setOnSceneChanged(EventHandler<? super SceneChangedEvent> handler) {
onSceneChanged.set(handler);
}
public final EventHandler<? super SceneChangedEvent> getOnSceneChanged() {
return onSceneChanged.get();
}
public final ObjectProperty<EventHandler<? super SceneChangedEvent>> onSceneChangedProperty() {
return onSceneChanged;
}
public CustomStage() {
this(StageStyle.DECORATED);
}
public CustomStage(#NamedArg(value = "style", defaultValue = "DECORATED") StageStyle style) {
super(style);
sceneProperty().addListener((obs, ov, nv) -> fireEvent(new SceneChangedEvent(this, ov, nv)));
}
}
This would let you react to the scene changing using any of the following:
CustomStage stage = new CustomStage();
// addEventFilter/addEventHandler
stage.addEventFilter(SceneChangedEvent.SCENE_CHANGED, e -> { ... });
stage.addEventHandler(SceneChangedEvent.SCENE_CHANGED, e -> { ... });
// setOnSceneChanged
stage.setOnSceneChanged(e -> { ... });
Keep in mind that the event will only target the CustomStage instance. In other words, only event handlers added to the CustomStage instance will be notified of the event. And as you can see, this is much more complicated than simply adding a change listener to the scene property of the Stage.
I have desktop app with side menu bar. Main window is BorderPane with InsertLeft containing VBox. I set Hbox buttons and their behaviour then I add them one by one to the VBox. InsertCenter has just Pane with alot of elements.
I've created 3 fxml files for each GUI layout.
sample.fxml - BorderPane: InsertLeft->Menu(VBox), InsertCenter->Empty Pane
tab1_content.fxml - Pane filled with ProgressBar, Labels and Buttons
tab2_content.fxml - Not yet implemented (Empty Pane)
Each of these fxml files has their controllers.
I would like to switch content of borderPane.center() inside sample.fxml on menu button click.
I've managed to fix some issues, but main problem is with loading data into .fxml views.
As I run my App it works perfectly, each fxml file has his FXMLLoader which will load content into borderPane right inside main Controller.
Problem occurs while I click on Buttons. It will switch panes, but actual content will reset to default state and Main.class initialization is completely ignored. Button listeners and label values are not initialized. It's just empty fxml layout. Every variable inside Main.class, what I want to access from Tab1Controller is returning NullPointerException - even methods.
Each controller extends AbstractController, which contains Main.class instance which is initialized inside start() method. So i should be able to have access to every Main.class method/variable at any time.
Issue Gif:
Some code samples:
My Main.class start() method:
public Controller myController;
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
myController = new Controller();
myController.setMainApp(this);
loader.setController(myController);
Parent root = loader.load();
primaryStage.setTitle("Simple App");
primaryStage.setScene(new Scene(root));
primaryStage.show();
<other stuff>
}
public void setDefaultViewProperties(){
currentScanningFileProperty = new SimpleStringProperty();
myController.tab1Controller.actualPath.textProperty().bind(currentScanningFileProperty); //NullPointerException while called from Controller
fileCounterProperty = new SimpleLongProperty();
myController.tab1Controller.numOfScanned.textProperty().bind(fileCounterProperty.asString());
maliciousFilesCounterProperty = new SimpleIntegerProperty();
myController.tab1Controller.numOfMaliciousFiles.textProperty().bind(maliciousFilesCounterProperty.asString());
myController.tab1Controller.fileChoiceBtn.setOnMouseClicked(event -> chooseFile());
myController.tab1Controller.runScanBtn.setOnMouseClicked(event -> new Thread(() -> {
try {
resetValues();
startFileWalking(chosenFile);
} catch (IOException e) {
e.printStackTrace();
}
}).start());
}
MainController:
package sample;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller extends AbstractController implements Initializable{
public HBox sideMenu;
public VBox mainMenu;
public BorderPane borderPane;
public Boolean isButton1Pressed = false;
public Boolean isButton2Pressed = false;
public static final String TAB_1 = "TAB-1";
public static final String TAB_2 = "TAB-2";
public Button malwareButton;
public Button webShieldButton;
public Tab1Controller tab1Controller;
public Tab2Controller tab2Controller;
#Override
public void initialize(URL location, ResourceBundle resources) {
createMenuButtons();
setSideMenu();
setMenuButtonsListeners();
}
private void setSideMenu(){
mainMenu.getChildren().add(item(malwareButton));
mainMenu.getChildren().add(item(webShieldButton));
mainMenu.setStyle("-fx-background-color:#004D40");
}
private HBox item(Button menuButton){
menuButton.setPrefSize(200, 50);
menuButton.setStyle("-fx-background-color: transparent;");
menuButton.setTextFill(Color.web("#E0F2F1"));
menuButton.setPadding(Insets.EMPTY);
sideMenu = new HBox(menuButton);
return sideMenu;
}
public void setMenuButtonsListeners(){
malwareButton.setOnMousePressed(event -> {
setButtonStylePressed(malwareButton);
setButtonStyleUnpressed(webShieldButton);
isButton1Pressed = true;
isButton2Pressed = false;
loadTab1Content();
main.setDefaultViewProperties();
});
webShieldButton.setOnMousePressed(event -> {
setButtonStylePressed(webShieldButton);
setButtonStyleUnpressed(malwareButton);
isButton1Pressed = false;
isButton2Pressed = true;
loadTab2Content();
});
malwareButton.setOnMouseExited(event -> {
if(!isButton1Pressed){
setButtonStyleUnpressed(malwareButton);
}
});
webShieldButton.setOnMouseExited(event -> {
if(!isButton2Pressed){
setButtonStyleUnpressed(webShieldButton);
}
});
malwareButton.setOnMouseEntered(event -> setButtonStylePressed(malwareButton));
webShieldButton.setOnMouseEntered(event -> setButtonStylePressed(webShieldButton));
}
public void setButtonStylePressed(Button btn){
btn.setStyle("-fx-background-color: #E0F2F1");
btn.setTextFill(Color.web("#004D40"));
}
public void setButtonStyleUnpressed(Button btn){
btn.setStyle("-fx-background-color: transparent");
btn.setTextFill(Color.web("#E0F2F1"));
}
private void loadTab1Content(){
FXMLLoader tab1loader = new FXMLLoader();
tab1loader.setLocation(getClass().getResource("/tab_1_content.fxml"));
try {
if (tab1Controller == null){
tab1Controller = new Tab1Controller();
}
tab1loader.setController(tab1Controller);
borderPane.setCenter(tab1loader.load());
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadTab2Content(){
FXMLLoader tab2loader = new FXMLLoader();
tab2loader.setLocation(getClass().getResource("/tab_2_content.fxml"));
try {
if (tab2Controller == null){
tab2Controller = new Tab2Controller();
}
tab2loader.setController(tab2Controller);
borderPane.setCenter(tab2loader.load());
} catch (IOException e) {
e.printStackTrace();
}
}
private void createMenuButtons(){
malwareButton = new Button();
malwareButton.setText(TAB_1);
webShieldButton = new Button();
webShieldButton.setText(TAB_2);
}
}
Tab1Controller:
package sample;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
/**
* Created by admin on 5. 5. 2018.
*/
public class Tab1Controller extends AbstractController implements Initializable {
public ProgressBar progressBar;
public Button runScanBtn;
public Button fileChoiceBtn;
public Label chosenPath;
public Label actualPath;
public Label numOfMaliciousFiles;
public Label hashValue;
public Label scanFinishedMsg;
public Label numOfScanned;
public Button showFoundMalwareButton;
#Override
public void initialize(URL location, ResourceBundle resources) {
runScanBtn.setDisable(true);
scanFinishedMsg.setVisible(false);
showFoundMalwareButton.setVisible(false);
showFoundMalwareButton.setOnAction(event -> showPopupWindow());
}
Update#1 - Updating fxml values through Main.class after button click
I've finally managed to run app without exception. I had to create next Controller for pane fxml layout itself called Tab1Controller. When I initialized Controller, it instantly initialized Tab1Controller inside. So when I want to change Center BorderPane label i had to call myController.tab1Controller.tabLabel.setText()
I don't know if it's good approach to this problem.
But now I'm back to my old problem. When I click on TAB-1 it will load content, but values are not initialized to default state.
For example I have couple of labels updated in real time. I binded some SimpleProperties into it with default values. It worked before, but as I have three controllers it will load data for a first time, but when I click TAB-1 button it will load just fxml content, but it will not set those labels.
So i made public method inside Main.class which I will call everytime I switch to TAB-1 from Controller.
public void setDefaultViewProperties(){
myController.tab1Controller.actualPath.textProperty().bind(currentScanningFileProperty);
myController.tab1Controller.numOfScanned.textProperty().bind(fileCounterProperty.asString());
myController.tab1Controller.numOfMaliciousFiles.textProperty().bind(maliciousFilesCounterProperty.asString());
}
But now everytime I click on TAB-1 I've got
java.lang.NullPointerException: Cannot bind to null
You can make two pane and switch between them using setVisible() method
example:
void btn1Clicked() {
pane1.setVisible(true);
pane2.setVisible(false);
}
void btn2Clicked() {
pane1.setVisible(false);
pane2.setVisible(true);
}
You could use a TabPane to achieve this behaviour:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TabPane.html
Solved. I'm not sure how, but setDefaultViewProperties() are not throwing NullPointerException at the moment. I did not change anything inside the code:
malwareButton.setOnMousePressed(event -> {
setButtonStylePressed(malwareButton);
setButtonStyleUnpressed(webShieldButton);
isButton1Pressed = true;
isButton2Pressed = false;
loadTab1Content();
main.setDefaultViewProperties();
});
A list of basic values is filtered by a (changing) predicate. The FilteredList is mapped to TreeItems and this resulting list is then used as the root TreeItems children.
When a selection was made on the TreeTableView and afterwards the predicate changes, accessing the selected items results in a NullPointerException.
It seems to me that items contained in the change are null. Is there a design flaw in this coarse concept?
This does not happen for the classes TreeView and ListView.
I tried to produce a MCVE using https://github.com/TomasMikula/EasyBind for the mapping:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.fxmisc.easybind.EasyBind;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Spinner;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class App extends Application {
// fields protect bound lists from GC
private ObservableList<DataItem> itemizedDataPool;
private FilteredList<Data> filteredDataPool;
private ObservableList<Data> selectedData;
static class Data {
final int value;
public Data(int value) {
this.value = value;
}
}
static class DataItem extends TreeItem<Data> {
final Data data;
public DataItem(Data data) {
this.data = data;
}
}
#Override
public void start(Stage primaryStage) throws IOException {
List<Data> dataPool = new ArrayList<Data>();
for (int i = 1; i < 20; i++) {
dataPool.add(new Data(i));
}
filteredDataPool = new FilteredList<>(FXCollections.observableArrayList(dataPool));
TreeTableView<Data> listView = createTreeTableView();
Spinner<?> lowerBoundSelector = createLowerBoundFilter();
Label sumLabel = createSummarizingLabel(listView.getSelectionModel().getSelectedItems());
Parent root = new VBox(listView, lowerBoundSelector, sumLabel);
Scene scene = new Scene(root, 768, 480);
primaryStage.setScene(scene);
primaryStage.show();
}
private TreeTableView<Data> createTreeTableView() {
itemizedDataPool = EasyBind.map(filteredDataPool, DataItem::new);
TreeItem<Data> itemRoot = new TreeItem<>();
Bindings.bindContent(itemRoot.getChildren(), itemizedDataPool);
TreeTableView<Data> listView = new TreeTableView<>(itemRoot);
listView.setShowRoot(false);
itemRoot.setExpanded(true);
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
listView.getColumns().add(new TreeTableColumn<>("Data"));
return listView;
}
private Label createSummarizingLabel(ObservableList<TreeItem<Data>> selectedItems) {
Label sumLabel = new Label();
selectedData = EasyBind.map(selectedItems, (TreeItem<Data> t) -> ((DataItem) t).data);
selectedData.addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
int sum = 0;
for (Data d : selectedData) {
sum += d.value;
}
sumLabel.setText("Sum: " + sum);
}
});
return sumLabel;
}
private Spinner<Integer> createLowerBoundFilter() {
Spinner<Integer> lowerBoundSelector = new Spinner<>(0, 20, 0, 1);
lowerBoundSelector.valueProperty().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
filteredDataPool.setPredicate(t -> t.value > lowerBoundSelector.getValue());
}
});
return lowerBoundSelector;
}
public static void main(String[] args) {
launch(args);
}
}
Problem
TreeTableView uses TreeTableViewArrayListSelectionModel, which extends MultipleSelectionModelBase, which uses ReadOnlyUnbackedObservableList, which uses (and contains) SelectionListIterator, which has a broken implementation for its method nextIndex.
Thanks to fabian for pointing that out.
He also filed a bug report (http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8145887).
Workaround
Using a buffer in between could provide an effective workaround for the problem above. I tried several approaches. setAll on selection invalidation and Bindings.bindContent do not work. In both cases I received null values in the list. The straightforward "solution" is to simply filter the nulls out. This leads to the inefficient but apparently effective code below.
// [...]
TreeTableView<Data> listView = createTreeTableView();
selectionBuffer = FXCollections.observableArrayList();
listView.getSelectionModel().getSelectedItems().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
selectionBuffer.clear();
for (TreeItem<Data> t : listView.getSelectionModel().getSelectedItems()) {
if (t != null) {
selectionBuffer.add(t);
}
}
}
});
// [...]
Using selectionBuffer instead of listView.getSelectionModel().getSelectedItems() should now compensate the implementation problem in nextIndex.
I have been stuck on this for a while and I am really at my last hope. I really have no idea what the problem can be. I have a GUI project using what I hope is correct MVP form and my problem is I have a presenter object that becomes null in my view class when being used within any method. So far the gui should load and user should hit the button, the method calls the presenter object's method to do something but it is always null. I tried passing into the view class's constructor, making it a object only within the view class, etc and I can't to fix it. Any help is appreciated. I have no idea what is going on and it does not seem to do this to any other object I think
main.java
package main;
import model.Model;
import presenter.Presenter;
import view.View;
public class Main
{
public static void main(String[] args)
{
View view = new View();
Model model = new Model();
Presenter presenter = new Presenter(view, model);
view.setPresenter(presenter);
// this was a way I found on stack overflow to call
// another class that inhierts the application class
// and be able to have args passed if needed
View.launch(View.class, args);
}
}
View.java
package view;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import presenter.Presenter;
public class View extends Application
{
private Presenter presenter;
private Button test;
private Views views;
public final static String LOGINVIEW = "loginscreen";
public final static String LOGINVIEWFILE = "FXMLViewLogin.fxml";
public final static String CHATVIEW = "chatscreen";
public final static String CHATVIEWFILE = "FXMLViewChat.fxml";
public View()
{
// init Views class
views = new Views();
}
public void setPresenter(Presenter pres)
{
this.presenter = pres;
}
#Override
public void start(Stage primaryStage)
{
loadViews();
primaryStage.setScene(setView(LOGINVIEW));
primaryStage.setTitle("");
primaryStage.show();
}
private void loadViews()
{
views.loadScreen(LOGINVIEW, LOGINVIEWFILE);
views.loadScreen(CHATVIEW, CHATVIEWFILE);
}
private Scene setView(String name)
{
return views.setView(name);
}
#FXML
private void test(ActionEvent event)
{
//***********************************************************
// ALWAYS NULL IN THIS EVENT METHOD METHOD AND ANY OTHER METHOD FOR THAT FACT AFTER setPresenter
if(presenter == null)
System.out.println("Why is this null right here?");
}
}
Presenter.java
package presenter;
import view.View;
import model.Model;
public class Presenter
{
private Model model;
private View view;
public Presenter(View view, Model model)
{
this.model = model;
this.view = view;
}
// any methods start here
}
Views.java
package view;
import java.util.HashMap;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Views
{
private final HashMap<String, Parent> view;
public Views()
{
this.view = new HashMap<>();
}
public void addView(String name, Parent screen)
{
view.put(name, screen);
}
public boolean loadScreen(String name, String file)
{
try
{
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(file));
Parent loadScreen = (Parent) myLoader.load();
addView(name, loadScreen);
return true;
}
catch (Exception e)
{
return false;
}
}
public Scene setView(final String name)
{
Scene scene = null;
if (view.get(name) != null)
scene = new Scene(getParentNode(name));
unloadView(name);
return scene;
}
private boolean unloadView(String name)
{
return view.remove(name) != null;
}
private Parent getParentNode(String name)
{
return view.get(name);
}
}