JavaFX 13:listview在打开和关闭新窗口后不会更新项目 [英] JavaFX 13 : listview does not update items after opening and closing new window

查看:62
本文介绍了JavaFX 13:listview在打开和关闭新窗口后不会更新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个将事件添加到列表中的程序,但是当我添加事件时,它在关闭addEvent Window之后不会更新列表,这是Senario:

i'm making a program that add events in a list but when i add event it doesn't update my list after closing addEvent Window , here is the senario :

1-这是第一个窗口:

1- this is the first window :

2-然后我按(+)按钮在addEvent窗口中添加事件:

2- then i press the (+) button to add event in addEvent window :

在这里,当我按确定"以测试我的代码时,我会添加测试"项

here i add "test" item when i press ok to test my code

3-现在我按下确定"按钮并返回主窗口:

3- now i press "ok" button and return to the main window :

现在我的列表中没有任何变化,并且没有显示该测试"项目,但是此项目"已经在列表中并成功添加.

now nothing change in my list and it doesn't show that "test" item but this "item" already in the list and added successfully.

这是所有代码:

  • 主班
    public static void main(String[] args) {

        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        FXMLLoader loader = new FXMLLoader(getClass().getResource("main_layout.fxml"));
        Parent root = (Parent) loader.load();   
        primaryStage.setTitle("Goba To Do List");
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
    }

  • MainController类
  •     @FXML
        private ListView<String> LeftSideListId; // this names just for testing
        @FXML
        private ListView<String> RightSideListId; // this names just for testing
        @FXML
        private Button AddEvent;
    
        public void initialize() throws Exception {
            System.out.println("init");
    
            ObservableList<String>eventsNamesList=FXCollections.observableArrayList(
                    "Daily Events","Custom Events","Completed Events");
    
            LeftSideListId.setItems(eventsNamesList);
    
            ObservableList<String>eventsList=FXCollections.observableArrayList(
                    "item1","item2","item3");
    
            RightSideListId.setItems(eventsList);
    
            AddEvent.setOnAction(new EventHandler<ActionEvent>() {
    
                @Override
                public void handle(ActionEvent arg0) {
                    AddButtonPressed();
                    }   
            });
        }
    
        void AddButtonPressed() {
    
            addEventController.DisplayAddEventWindow();
    
        }
        public void DisplayAddEventWindow()
         {
             try {
                 Stage primaryStage = new Stage();
                 primaryStage.setTitle("Add Event");
                 Scene scene = new Scene(AddEventScene);
                 primaryStage.initModality(Modality.APPLICATION_MODAL);
                 primaryStage.setScene(scene);
                 primaryStage.setResizable(false);
                 primaryStage.show();
             }
             catch(Exception e) 
             {
                 e.printStackTrace();
             }
         }
    
        public void RefreshList() {
            System.out.println("refresh");
    
            RightSideListId.getItems().add("test");
            System.out.println(RightSideListId.getItems()); // here i get [item1,item2,item3,test]
        }
    
    

    • AddEventController类
    •     @FXML
          private Button BtnOk;
          @FXML
          private Button BtnCancel;
      
          public void initialize() throws Exception {
      
               BtnOk.setOnAction(new EventHandler<ActionEvent>() {
                   @Override
                   public void handle(ActionEvent arg0) {
                       try {
                          BtnOkPressed();
                      } catch (Exception e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                   }  
               });
               BtnCancel.setOnAction(new EventHandler<ActionEvent>() {
                   @Override
                   public void handle(ActionEvent arg0) {
                       BtnCancelPressed();
                   }  
               });    
           }
      
           public void BtnCancelPressed() {
               Stage stg= (Stage)BtnCancel.getScene().getWindow();
               stg.close();
      
          }
      
          public void BtnOkPressed() throws Exception {
               Stage stg= (Stage)BtnOk.getScene().getWindow();
               stg.close();
               FXMLLoader loader = new FXMLLoader(getClass().getResource("main_layout.fxml"));
               Parent root = (Parent) loader.load();
               MainController mainController=loader.getController();
               mainController.RefreshList();
          }
      
      

      那我在这里做错了什么?

      so what i did wrong here ?

      如果我没有打开任何窗口,则列表会正常更新,因此仅在同一窗口中时才会更新... idk为什么

      my list updates normally if i didn't open any windows so it is updating only while in the same window... idk why

      推荐答案

      我创建了一个演示解决方案的示例.此解决方案使用了来自Jewelsea的答案的建议此处.基本上,打开一个新窗口,然后在关闭窗口时使用Optional返回String或不返回任何内容.这是一个快速的答案.我仍然更喜欢Jame_D的MVC想法,而不是这个答案.此解决方案并不意味着是完美的.这只是显示解决问题的方法.

      I created an Example that demos a solution. This solution uses ideas from Jewelsea's answer here. Basically, open a new window and when you close the window return a String or nothing using Optional. This is a quick answer. I still prefer Jame_D's MVC ideas over this answer. This solution is not meant to be perfect. It's only to show a way to solve the problem.

      主要

      import javafx.application.Application;
      import javafx.fxml.FXMLLoader;
      import javafx.scene.Parent;
      import javafx.scene.Scene;
      import javafx.stage.Stage;
      
      import java.io.IOException;
      
      /**
       * JavaFX App
       */
      public class App extends Application {
      
          private static Scene scene;
      
          @Override
          public void start(Stage stage) throws IOException {
              scene = new Scene(loadFXML("primary"), 640, 480);
              stage.setScene(scene);
              stage.show();
          }
      
          private static Parent loadFXML(String fxml) throws IOException {
              FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
              return fxmlLoader.load();
          }
      
          public static void main(String[] args) {
              launch();
          }
      
      }
      

      主控制器

      import java.io.IOException;
      import java.net.URL;
      import java.util.Optional;
      import java.util.ResourceBundle;
      import javafx.collections.FXCollections;
      import javafx.collections.ObservableList;
      import javafx.fxml.FXML;
      import javafx.fxml.FXMLLoader;
      import javafx.fxml.Initializable;
      import javafx.scene.Scene;
      import javafx.scene.control.Button;
      import javafx.scene.control.ListView;
      import javafx.stage.Stage;
      
      public class PrimaryController implements Initializable{
          @FXML ListView<String> lvMain;
          @FXML Button btnAddNewItem;
      
          ObservableList<String>eventsList = FXCollections.observableArrayList("item1","item2","item3");
      
          @Override
          public void initialize(URL url, ResourceBundle rb) {    
              lvMain.setItems(eventsList);
      
              btnAddNewItem.setOnAction((actionEvent) ->
              {
                  try
                  {
                      FXMLLoader addNewItemLoader = new FXMLLoader(getClass().getResource("secondary.fxml"));
                      Stage secondStage = new Stage();
                      secondStage.setScene(new Scene(addNewItemLoader.load()));
                      SecondaryController addNewItemController = addNewItemLoader.getController();                  
                      secondStage.showAndWait();
                      Optional<String> result = addNewItemController.getNewItem();
                      if (result.isPresent()){
                          System.out.println("Your name: " + result.get());
                          eventsList.add(result.get());
                      }
                  }
                  catch (IOException e)
                  {
                      System.out.println(e.toString());
                  }            
              });        
          }
      }
      

      主要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.VBox?>
      
      <VBox alignment="CENTER" prefHeight="393.0" prefWidth="508.0" spacing="20.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sed.test.javafxfxmltestinggrounds.PrimaryController">
         <padding>
            <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
         </padding>
         <children>
            <ListView fx:id="lvMain" prefHeight="200.0" prefWidth="200.0" />
            <Button fx:id="btnAddNewItem" mnemonicParsing="false" text="+" />
         </children>
      </VBox>
      

      辅助控制器(添加新项目"窗口)

      import java.net.URL;
      import java.util.Optional;
      import java.util.ResourceBundle;
      import javafx.fxml.FXML;
      import javafx.fxml.Initializable;
      import javafx.scene.control.Button;
      import javafx.scene.control.TextArea;
      import javafx.stage.Stage;
      
      public class SecondaryController implements Initializable{
      
          @FXML TextArea taSecondary;
          @FXML Button btnOk, btnCancel;
      
          Optional<String> returnValue;
      
          @Override
          public void initialize(URL url, ResourceBundle rb) {          
              btnOk.setOnAction((actionEvent) ->
              {
                  returnValue = Optional.of(taSecondary.getText());
                  ((Stage)(((Button)actionEvent.getSource()).getScene().getWindow())).close();
      
              });   
      
              btnCancel.setOnAction((actionEvent) ->
              {
                  returnValue = Optional.empty();
                  ((Stage)(((Button)actionEvent.getSource()).getScene().getWindow())).close();
              });
          }
      
          public Optional<String> getNewItem()
          {
              return returnValue;
          }
      }
      

      辅助FXML

      <?xml version="1.0" encoding="UTF-8"?>
      
      <?import javafx.geometry.Insets?>
      <?import javafx.scene.control.Button?>
      <?import javafx.scene.control.TextArea?>
      <?import javafx.scene.layout.HBox?>
      <?import javafx.scene.layout.VBox?>
      
      <VBox alignment="CENTER" spacing="20.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sed.test.javafxfxmltestinggrounds.SecondaryController">
          <padding>
              <Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
          </padding>
         <children>
            <TextArea fx:id="taSecondary" prefHeight="200.0" prefWidth="200.0" />
            <HBox alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" spacing="5.0">
               <children>
                  <Button fx:id="btnOk" mnemonicParsing="false" prefWidth="52.0" text="OK" />
                  <Button fx:id="btnCancel" mnemonicParsing="false" prefWidth="52.0" text="Cancel" />
               </children>
            </HBox>
         </children>
      </VBox>
      

      这篇关于JavaFX 13:listview在打开和关闭新窗口后不会更新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆