Add data to static ComboBox in JavaFX 2.2 - java

I just can't figure out how to add data to static ComboBox in JavaFX 2.2. Whatever I try to do ComboBox is empty. Here is the code:
#FXML private MenuItem menuItemNewTile;
#FXML private static ComboBox<Tile> comboBoxTileList;
#FXML
private void menuItemNewTileSetOnAction(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource(TILE_WINDOW_URL));
Scene scene = new Scene(root);
Stage tileStage = new Stage();
tileStage.setScene(scene);
tileStage.show();
}
#FXML
private void comboBoxTileListSetOnAction(ActionEvent event) {
}
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
comboBoxTileList = new ComboBox<>();
}
public static void refreshTileList(Tile tile) {
comboBoxTileList.getItems().add(tile);
}
If ComboBox is private, and I add item in initialize method it's working, but with static ComboBox I tried million things and still no progress.

Solution
Don't use static and #FXML together.
Rework your design so that the static keyword is no longer required for the comboBoxTileList and use an instance variable instead.
Additional Issue
An #FXML member such as comboBoxTileList should never be set to a new value, so you should not have comboBoxTileList = new ComboBox<>();
Answer to additional questions
I use another window to create new Tile object and from controller class of that window i call refreshTileList method. How to do that without using static?
There are numerous ways of writing your code so that you don't need a static reference to controller members. Here is a sample based on a solution from: Passing Parameters JavaFX FXML. You will need to modify the example to fit your exact case, it's just presented to demonstrate a possible pattern that you could use.
You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load() instance method.
To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller attribute in your fxml file.
class ComboController {
#FXML private static ComboBox<Tile> comboBoxTileList;
public void refreshTileList(Tile tile) {
comboBoxTileList.getItems().add(tile);
}
}
class AnotherController {
#FXML private Button createTile;
#FXML private Button newCombo;
#FXML private StackPane mainPane;
private comboController;
#FXML private void createTile(ActionEvent event) {
if (comboController == null) {
return;
}
comboController.refreshTileList(
new Tile()
);
}
#FXML private void newCombo(ActionEvent event) {
try {
comboController = new ComboController();
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"combo.fxml"
)
);
loader.setController(comboController);
Pane comboPane = (Pane) loader.load();
mainPane.getChildren().setAll(comboPane);
} catch (IOException e) {
// handle exception.
}
}
}

Related

Java updating Table view cell values from another class

I am trying to change one of my columns and its cell values from another class however i keep getting a null pointer exception when java try's to execute that line OverviewController.getOverviewController.returnStatusColumn.setCellValueFactory(
cellData -> cellData.getValue().getStatusProperty());, I have removed all irreverent code
TableView Class:
#FXML
private TableView<Task> taskTable;
#FXML
private TableColumn<Task, String> statusColumn;
private final static OverviewController controller = new OverviewController
();
public static OverviewController getOverviewController() {
return controller;
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
taskTable.setItems(mainApp.getTaskData());
taskTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
taskTable.setPlaceholder(new Label(""));
}
public TableView<taskTable> returnTasks() {
return taskTable;
}
public TableColumn<taskTable, String> returnStatusColumn() {
return statusColumn;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
statusColumn.setCellValueFactory(cellData ->
cellData.getValue().getStatusProperty());
}
#FXML
public void createTask(ActionEvent event) throws InterruptedException,
IOException, ParseException {
thread = new MyThread();
thread.main(null);
statusColumn.setCellValueFactory(cellData ->
cellData.getValue().getStatusRunningProperty());
statusColumn.setStyle("-fx-text-fill: green; -fx-font-weight: bold;");
taskTable.refresh();
}
#FXML
public void stopTasks() {
statusColumn.setCellValueFactory(cellData ->
cellData.getValue().getStatusProperty());
statusColumn.setStyle("-fx-text-fill: red; -fx-font-weight: bold;");
taskTable.refresh();
}
This class works fine when i want to update the table columns, if i click stop tasks method (which is linked to a button) the status column gets updated to the stop label which i want to do, same with start tasks method.
Random class where i want to update the Table view status column:
public class UpdateTable {
public static void main(String[] args) {
OverviewController.getOverviewController.returnStatusColumn.setCellValueFactory(
cellData -> cellData.getValue().getStatusProperty());
OverviewController.getOverviewController().returnTasks().refresh();
}
}
TableView Data:
//Status Information
private final SimpleStringProperty status;
private final SimpleStringProperty statusRunning;
public Task() {
this(null, null);
}
public Task() {
this.statusRunning = new SimpleStringProperty("Running");
this.status= new SimpleStringProperty("Stop");
}
public StringProperty getStatusProperty( ) {
return status;
}
public StringProperty getStatusRunningProperty( ) {
return statusRunning;
}
}
If i ran the random class it will lead to a null pointer exception in particular this line:
OverviewController.getOverviewController().returnStatusColumn().setCellValueFactory(cellData -> cellData.getValue().getStatusProperty());
Have i done this completely the wrong way? I just want to be able to update the Table view column cells from a different class.
Yes, you're doing this the wrong way.
You don't use a Application subclass anywhere which needs to be used as entry point of your application (assuming you're not using JFXPanel or Platform.startup). Furthermore you access the column as first statement in your program which means there's no way the statusColumn field is initialized.
Also usually there shouldn't be a need to involve any class but the controller class for initializing the cellValueFactory. Especially using static fields is a bad approach:
Assuming you specify the controller class in the fxml, FXMLLoader creates a new instance of the controller class. This instance is different from the instance stored in the controller field so even when using
OverviewController.getOverviewController.returnStatusColumn.setCellValueFactory(
cellData -> cellData.getValue().getStatusProperty());
after loading the fxml you wouldn't get the instance you need.
Instead I recommend using the initialize method of the controller class for these kind of initialisations. It's invoked by FXMLLoader after creating and injecting all the objects specified in the fxml.
public class OverviewController {
...
#FXML
private TableColumn<Task, String> statusColumn;
...
#FXML
private void initialize() {
statusColumn.setCellValueFactory(cellData -> cellData.getValue().getStatusProperty());
}
}
If you do need to pass some info from an class that is not the controller, refer to the answers here Passing Parameters JavaFX FXML . Better approaches than using static are described in the answers.

#FXML Annotation not working correctly

I'm currently working on a 'small' project with JavaFX. I used the SceneBuilder to create the first sketch of my GUI. it still needs some adjustment and styling but I wanted to see if it's working so far.
I have 2 hyperlinks on the GUI, if the user clicks one of them the default system-browser should open with a specific URL.
So far I got this:
Main.java:
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws MalformedURLException, IOException {
DataBean dataBean= new DataBean(primaryStage);
Controller controller = new Controller(dataBean);
controller.show();
}
public static void main(String[] args) {
launch(args);
}
}
DataBean.java:
public class DataBean {
private Stage primaryStage;
public DataBean(Stage stage) {
primaryStage = stage;
}
public Stage getPrimaryStage() {
return primaryStage;
}
}
TestautomatView.java:
public class TestautomatView implements Initializable {
#FXML
private ComboBox<String> environmentCombo;
#FXML
private Hyperlink crhl;
#FXML
private Hyperlink help;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
private Scene scene;
private BorderPane root;
public TestautomatView() throws MalformedURLException, IOException {
root = FXMLLoader.load(new URL(TestautomatView.class.getResource("Sample.fxml").toExternalForm()));
scene = new Scene(root);
}
public void show(Stage stage) {
stage.setTitle("CrossReport Testautomat");
stage.setScene(scene);
stage.show();
}
public ComboBox<String> getEnvironmentCombo() {
return environmentCombo;
}
public Hyperlink getCrhl() {
return crhl;
}
public Hyperlink getHelp() {
return help;
}
public Scene getScene() {
return scene;
}
}
In my controller I want to set the ActionHandler to the hyperlinks but it's not working because the getters in my view return null.
public class Controller {
private DataBean dataBean;
private TestautomatView view;
public Controller(DataBean databean) throws MalformedURLException, IOException {
this.dataBean = databean;
this.view = new TestautomatView();
setActionHandlers();
}
public void show() throws MalformedURLException, IOException {
view.show(dataBean.getPrimaryStage());
}
private void setActionHandlers() {
// setHyperlink(view.getCrhl(), "www.example.com");
// setHyperlink(view.getHelp(), "www.example2.com");
}
private void setHyperlink(Hyperlink hl, String uri) {
hl.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//TODO - Open Default Browser
}
});
}
}
When I start my application, I can see the GUI but when I want to add the ActionHandlers I get a NullPointerException.
In the ´Sample.fxml´ file the hyperlinks are children of a HBox
<Hyperlink fx:id="crhl" text="Report" />
<Hyperlink fx:id="help" text="Help" />
But it's not just the hyperlinks even the ComboBox is null when I inspect my app in the debugger.
Where is my mistake?
The problem is that you are creating your controller manually by using new TestautomatView(). It must be created by FXMLLoader for annotations to work. You must also set fx:controller attribute in Sample.fxml to your controller (TestautomatView) fully qualified class name.
Example code:
FXMLLoader fl = new FXMLLoader(new URL(TestautomatView.class.getResource("Sample.fxml").toExternalForm()));
root = fl.load();
TestautomatView controller = fl.getController();
PS: You should rename your TestautomatView to TestautomatController. FXML file is your "view".
As pointed out in another answer, the issue is that you create an instance of TestautomatView "by hand". The default behavior of the FXMLLoader is to create an instance of the controller class specified in the FXML file, and use that instance as the controller. Consequently, you have two instances of TestautomatView: the one you created (and have a reference to), and the one that was created by the FXMLLoader. It is the second one that has the #FXML-annotated fields initialized.
You can change this default behavior by creating an FXMLLoader instance, and setting the controller on it directly. E.g. consider doing:
public class TestautomatView implements Initializable {
#FXML
private ComboBox<String> environmentCombo;
#FXML
private Hyperlink crhl;
#FXML
private Hyperlink help;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
private Scene scene;
private BorderPane root;
public TestautomatView() throws MalformedURLException, IOException {
FXMLLoader loader = new FXMLLoader(TestautomatView.class.getResource("Sample.fxml"));
loader.setController(this);
root = loader.load();
scene = new Scene(root);
}
// etc...
}
Since you are directly setting the controller, you need to remove the fx:controller attribute from the Sample.fxml file for this to work.
You may also be interested in this pattern, which is quite similar (though not exactly the same) as what you are trying to do here.

Why does adding a View after initialization throws NLP but not during initialization, using afterburner.fx

I am using afterburner.fx http://afterburner.adam-bien.com/
It works as advertised. I can add multiple fxml Files to a central/main "view".
But if I want to add another fxml/presenter later, for example, using a button on a different navigationPane to add another fxml to the mainAnchorPane.
Then it throws a NullPointerException.
public class MainscenePresenter implements Initializable {
#FXML
AnchorPane breadcrumbAnchor;
#FXML
AnchorPane navigationAnchor;
//--------------------------------------------------------
#FXML
private AnchorPane mainAnchorPane; //ADD NEW ATPANE HERE
private AtPresenter atPresenter;
private AtView atView;
//--------------------------------------------------------
#Override
public void initialize(URL url, ResourceBundle rb) {
//add BreadCrumBar WORKS
BreadcrumbbarView breadcrumbbarView = new BreadcrumbbarView();
breadcrumbbarView.getViewAsync(breadcrumbAnchor.getChildren()::add);
//add DFD WORKS
DfdView dfdView = new DfdView();
Parent view2 = dfdView.getView();
this.mainAnchorPane.getChildren().add(view2);
//add Navigation WORKS
NavigationView navigationView = new NavigationView();
Parent view = navigationView.getView();
navigationAnchor.getChildren().add(view);
//add AT
this.atView = new AtView();
this.atPresenter = (AtPresenter) this.atView.getPresenter();
//ADDING AT VIEW LIKE THIS WORKS <=========================
this.showAt();
}
void showAt() {
this.mainAnchorPane.getChildren().add(this.atView.getView()); // <== NLP here if invoked with buttonAt
}
public void buttonAt() {
//ADDING AT VIEW LIKE THIS(Button on different Presenter) DOES NOT WORK => NLP
this.showAt();
}
}
public class NavigationPresenter implements Initializable {
#FXML
Button atNavButton;
#Inject
MainscenePresenter mainscene;
private ResourceBundle resources = null;
#Override
public void initialize(URL location, ResourceBundle resources) {
this.resources = resources;
}
#FXML
void showDfdScene(ActionEvent event) {
mainscene.buttonAt();
}
}
It seems I don't understand some central mechanism of JavaFX! And can't name it, to look it up!
Why does it throw NullPointerException in this case and not durin initialization?
Caused by: java.lang.NullPointerException
at abc.abc.app.mainscene.MainscenePresenter.showAt(MainscenePresenter.java:107)
at abc.abc.app.mainscene.MainscenePresenter.buttonAt(MainscenePresenter.java:112)
at abc.abc.app.navigation.NavigationPresenter.showDfdScene(NavigationPresenter.java:41)
... 58 more
Afterburner.fx is a dependency-injection framework for JavaFX. The main functionality it provides is the ability to inject objects into the controllers/presenters that are created when you load an FXML file (by instantiating a subclass of FXMLView). The basic process that happens when you instantiate a FXMLView is:
A new instance of the corresponding presenter is created
The presenter is inspected to find any #Inject-annotated fields
For each #Inject-annotated field, if an instance of that type exists in the injector's cache, it is set as the value of that field. Otherwise, a new instance of that type is created and placed in the cache, and set as the value of the field.
The main point to note here is that the presenters themselves are treated differently to their dependencies. If you try (as in your code) to inject one presenter in another, an instance of the presenter class will be created specifically for injection purposes: this will not be the same instance that is created when the FXML file is loaded, and consequently it won't have any #FXML-fields injected. This is why you get a null pointer exception: mainAnchorPane is null in the ``MainScenePresenterthat is injected into theNavigationPresenter`.
One presenter having a reference to another is generally a bad idea anyway: it creates unnecessary coupling between the two presenters. Instead, you should inject a model into both presenters that represents the state you want to share between them. In your case you might have something like
public class ViewState {
private final BooleanProperty atShowing = new SimpleBooleanProperty();
public BooleanProperty atShowingProperty() {
return atShowing ;
}
public final boolean isAtShowing() {
return atShowingProperty().get();
}
public final void setAtShowing(boolean atShowing) {
atShowingProperty().set(atShowing);
}
}
Now in your presenters, do
public class MainscenePresenter implements Initializable {
#Inject
private ViewState viewState ;
#FXML
AnchorPane breadcrumbAnchor;
#FXML
AnchorPane navigationAnchor;
//------------------------------------------------------
#FXML
private AnchorPane mainAnchorPane; //ADD NEW ATPANE HERE
private AtPresenter atPresenter;
private AtView atView;
//------------------------------------------------------
#Override
public void initialize(URL url, ResourceBundle rb) {
//add BreadCrumBar WORKS
BreadcrumbbarView breadcrumbbarView = new BreadcrumbbarView();
breadcrumbbarView.getViewAsync(breadcrumbAnchor.getChildren()::add);
//add DFD WORKS
DfdView dfdView = new DfdView();
Parent view2 = dfdView.getView();
this.mainAnchorPane.getChildren().add(view2);
//add Navigation WORKS
NavigationView navigationView = new NavigationView();
Parent view = navigationView.getView();
navigationAnchor.getChildren().add(view);
//add AT
this.atView = new AtView();
this.atPresenter = (AtPresenter) this.atView.getPresenter();
this.viewState.atShowingProperty().addListener((obs, wasShowing, isNowShowing) -> {
if (isNowShowing) {
this.mainAnchorPane.getChildren().remove(this.atView.getView());
} else {
this.mainAnchorPane.getChildren().add(this.atView.getView());
}
});
}
}
and
public class NavigationPresenter implements Initializable {
#FXML
Button atNavButton;
#Inject
private ViewState viewState ;
private ResourceBundle resources = null;
#Override
public void initialize(URL location, ResourceBundle resources) {
this.resources = resources;
}
#FXML
void showDfdScene(ActionEvent event) {
viewState.setAtShowing(true);
}
}

Auto Updating Tableview in JAVA Fx

In my project when a client will be disconnected, server will delete the name from observable list and the tableview should stop showing the name. But the tableview is not updating.
Controller class
public class Controller {
#FXML
public TableView tableView;
#FXML
private TableColumn<clientLoginData,String> client;
#FXML
private TableColumn<clientLoginData,String> activeTime;
void initialize(ObservableList<clientLoginData> data)
{
client.setCellValueFactory(new PropertyValueFactory<>("clientName"));
client.setCellFactory(TextFieldTableCell.<clientLoginData>forTableColumn());
activeTime.setCellValueFactory(new PropertyValueFactory<>("time"));
activeTime.setCellFactory(TextFieldTableCell.<clientLoginData>forTableColumn());
tableView.setItems(data);
tableView.setEditable(true);
}
}
main class
public class Main extends Application{
volatile public ObservableList<clientLoginData> data= FXCollections.observableArrayList();
public Controller controller;
#Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("server.fxml"));
Parent root = loader.load();
data.addAll(new clientLoginData((new SimpleStringProperty("john")),new SimpleStringProperty(ZonedDateTime.now().getHour()+":"+ZonedDateTime.now().getMinute())));
controller=loader.getController();
controller.initialize(data);
primaryStage.setTitle("Server");
primaryStage.setScene(new Scene(root, 600, 400));
primaryStage.show();
Thread t=new Thread(new messengerServer(this));
t.start();
}
public static void main(String[] args) {
launch(args);
}
}
updating class
public class messengerReadThread implements Runnable {
private Thread thr;
private NetworkUtil nc;
public Hashtable<SimpleStringProperty, NetworkUtil> table;
SimpleStringProperty oldName;
Main main;
public messengerReadThread(NetworkUtil nc, Hashtable<SimpleStringProperty, NetworkUtil> table, SimpleStringProperty s, Main main) {
this.nc = nc;
this.thr = new Thread(this);
thr.start();
this.table=table;
oldName=s;
this.main=main;
}
public void run() {
try {
while(true) {
String s1=(String)nc.read();
StringTokenizer st=new StringTokenizer(s1);
if(st.nextToken().equals("Name"))
{
String sn=s1.substring(5,s1.length());
NetworkUtil n1=table.get(oldName);
table.remove(oldName);
oldName=new SimpleStringProperty(sn);
table.put(oldName, n1);
main.data.add(new clientLoginData(oldName,new SimpleStringProperty(ZonedDateTime.now().getHour()+":"+ZonedDateTime.now().getMinute())));
}
else
{
System.out.println("here it is"+s1);
}
}
} catch(Exception e) {
System.out.println("disconnected "+oldName.toString());
main.data.remove(oldName);
//System.out.println(main.data.contains(oldName));
main.controller.tableView.refresh();//the tableview should update
}
nc.closeConnection();
}
}
There are some modification I should to to that code, like avoid using those "static references", by defining the ObservableList and move your Updating Code inside Controller so you can have a 2 classes code, the Main Class and your Controller... but i'll try to keep it simple.
First, you need to define the ObservableList inside you controller.
Then place your "updating" code inside the controller in a method. I suggest you to use a Task<> to keep your controller updated in the JavaFX Thread.
Try something like this:
private void updateTable(){
Task<Void> myUpdatingTask=new Task<Void>() {
#Override
protected Void call() throws Exception {
//Your Updating Code Here
}
}
//and then you run it like this:
Thread hilo=new Thread(myUpdatingTask);
hilo.setDaemon(true);
hilo.start();
}
Then, remove the parameter from your Initialize Method and define it private with the #FXML annotation like this:
#FXML
private void initialize(){
//Your Stuff to initialize
//here is were you fill your table like you did in the Main
//and don't forget to call you updateTable Method
this.updateTable();
}
Since this a dirty hack as pointed out by #kleopatra I am going to decorate it as a dirty hack.
****************************Dirty Hack*****************************************
Try hiding a column and displaying it again and your tableview should refresh

Set Reference Application from Controller?

New to JAVAFX so this maybe a simple fix, but I have controllers in my application setup using FXML files. I reference the controller to use via the FXML file and to load the file i use the following code in my Application class
private void replaceScene(String resource) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource(resource));
Pane screen = (Pane) loader.load();
Scene scene = new Scene(screen);
scene.getStylesheets().addAll(getClass().getResource("/css/application.css").toExternalForm());
stage.setScene(scene);
stage.sizeToScene();
IControlledScreen controller = (IControlledScreen) loader.getController();
controller.setApp(this);
} catch (Exception e) {
System.out.println("Cannot load resource " + resource);
System.out.println(e.getMessage());
}
}
And here is a basic controller
public class MyController implements IControlledScreen {
MyApplication app;
public void setApp(MyApplication application) {
app = application;
}
#FXML
public Button btnStart;
// Initialises the controller class.
#FXML
protected void initialize() {
btnStart.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
// code here
}
});
}
}
I have also got an interface called IControlledScreen to set the reference to the application
public interface IControlledScreen {
// ALlows us a reference to the application
public void setApp(MyApplication app);
}
Now this all works fine, until i try to access the app variable during the initialize event. So changing the above controller to this now breaks, because app = NULL.
public class MyController implements IControlledScreen {
MyApplication app;
public void setApp(MyApplication application) {
app = application;
}
#FXML
public Button btnStart;
// Initialises the controller class.
#FXML
protected void initialize() {
// HERE app = NULL
app.GetSomeProperty = "";
}
}
How can i get round this?
Well I think you have to change your design.
The initialize method is called during FXMLLoader.load()
So the call stack would be something like
..replaceScene
..loader.load
....MyController.initialize()
..loader.getController
..controller.setApp(app)
If you really have to access the application from inside your controller you would need to make it a singleton.

Categories