2017-01-09 3 views
0

У меня возникли трудности с решением этой проблемы, и я не могу найти правильный ответ на эту проблему, которую я имею. Я хочу, чтобы сцена/сцена использовалась в качестве кнопки для открытия другой сцены/сцены, и оба вызываются этим же методом. Вот полный метод:Использование сцены/сцены как кнопки для открытия другой сцены/этапа

public void createChatWindowMinimized(int agentKey, String message) 
    {    
     LOGGER.enterMethod(); 

     try{     
      ChatAgentsController chatController = null; 

      User agent = getModel().getRealtimeAgentNode().getUser(agentKey); 
      String firstNameLastName = agent.getFirstname() + " " + agent.getLastName(); 

      UserAvatar userAvatar = getModel().getRealtimeAgentNode().getUserAvatar(agentKey); 

      ImageView agentAvatar; 

      agentAvatar = new ImageView(); 

      Stage toastStage = new Stage(); 
      toastStage.initStyle(StageStyle.UNDECORATED); 
      toastStage.setHeight(120); 
      toastStage.setWidth(250); 


      BorderPane toastBorderPane = new BorderPane(); 
      Scene toastScene = new Scene(toastBorderPane); 
      toastScene.getStylesheets().add(this.getClass().getResource("MessageToaster.css").toExternalForm()); 

      if(userAvatar == null || userAvatar.getBuffer() == null)        
       agentAvatar.getStyleClass().add("AgentDefaultAvatar"); 
      else    
       agentAvatar.setImage(new Image(new ByteArrayInputStream(userAvatar.getBuffer()), 48, 48, true, true)); 

      VBox vboxToastImage = new VBox(); 
      vboxToastImage.getStyleClass().add("ToasterImage");     
      ImageView imgToastAgent = agentAvatar; 
      imgToastAgent.setFitHeight(60); 
      imgToastAgent.setFitWidth(60);     
      vboxToastImage.getChildren().add(imgToastAgent); 
      toastBorderPane.setLeft(vboxToastImage); 

      VBox vboxInCenter = new VBox(); 
      Label userName = new Label(firstNameLastName); 
      userName.getStyleClass().add("ToasterUserName"); 

      Text toasterContent = new Text(message); 
      toasterContent.getStyleClass().add("ToasterMessage"); 

      vboxInCenter.getChildren().addAll(userName, toasterContent); 
      vboxInCenter.getStyleClass().add("ToasterBox"); 
      toastBorderPane.setCenter(vboxInCenter); 
      toastBorderPane.getStyleClass().add("ToasterBorderPane"); 


      Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds(); 

      toastStage.setX(primaryScreenBounds.getMinX() + primaryScreenBounds.getWidth() - TOASTER_WINDOW_WIDTH); 
      toastStage.setY(primaryScreenBounds.getMinY() + primaryScreenBounds.getHeight() - TOASTER_WINDOW_HEIGHT);     
      toastStage.setScene(toastScene); 
      // check if a chat window for this user already exists 
      if (chatAgentsMap.containsKey(agentKey)) 
      { 
       // chat window has been created 
       chatController = chatAgentsMap.get(agentKey); 
       LOGGER.message(String.format("Showing chat window for agent '%d'.", agentKey));      
       if(!chatController.getChatStage().isFocused()){ 
        toastStage.show(); 
        chatController.getChatStage().show(); 
       } 
      } 
      else 
      { 
       // create new chat window      
       LOGGER.message(String.format("Creating chat window for agent '%d'.", agentKey));      
       chatController = ChatAgentsController.create(this, agentKey, connectedToOpenfireServer, true); 
       toastStage.show(); 
       toastStage.setAlwaysOnTop(true); 

       //-----Here is where I want that the toastStage or the toastScene is clickable by mouse and that it opens the window already created chatController 


       chatController.getChatStage().show(); 
       chatAgentsMap.put(agentKey, chatController); 
      } 

      if (chatController != null && message != null) // append received message to the chat text area 
       chatController.addChatEntry(agentKey, message); 
     } 
     catch (Throwable t) 
     { 
      LOGGER.error(t); 
     } 
     finally 
     { 
      LOGGER.leaveMethod(); 
     } 
    } 

Я все время пытался использовать событие мыши из CLICK, но я не работаю, потому что мои переменные, экземпляр другого окна (chatController.getChatStage() шоу().) Не является окончательный.

ответ

1

Просто удалите текущее объявление и инициализацию chatController:

// ChatAgentsController chatController = null; 

и объявить и инициализировать ее один раз, перед первым if заявление. Это было это эффективно окончательным и может быть использовано в лямбда-выражения:

boolean controllerExisted = chatAgentsMap.containsKey(agentKey) ; 

ChatAgentsController chatController = chatAgentsMap.computeIfAbsent(agentKey, k -> { 
    LOGGER.message(String.format("Creating chat window for agent '%d'.", k)); 
    return ChatAgentsController.create(this, k, connectedToOpenfireServer, true); 
}); 

if (controllerExisted) { 
    // chat window has been created 
    // chatController = chatAgentsMap.get(agentKey); 
    LOGGER.message(String.format("Showing chat window for agent '%d'.", agentKey));      
    if(!chatController.getChatStage().isFocused()){ 
     toastStage.show(); 
     chatController.getChatStage().show(); 
    } 
} else { 

    // chatController = ChatAgentsController.create(this, agentKey, connectedToOpenfireServer, true); 
    toastStage.show(); 
    toastStage.setAlwaysOnTop(true); 

    //-----Here is where I want that the toastStage or the toastScene is clickable by mouse and that it opens the window already created chatController 

    toastScene.setOnMouseClicked(e -> chatController.getChatStage().show()); 

    // chatAgentsMap.put(agentKey, chatController); 
} 
+0

Здесь: ChatAgentsController chatController = chatAgentsMap.computeIfAbsent (agentKey, к -> { LOGGER.message (string.Format ("Создание окно чата для агента '% d'., k)); return ChatAgentsController.create (это, k, connectedToOpenfireServer, true); }); он просит поставить try-catch, но когда я это сделаю, он все еще показывает пару ошибок. Один из них - это неправильный тип возврата в лямбда-выражении. –

+0

Итак, 'ChatAgentsController.create (...)' объявляет проверенное исключение? Объединяя оператор 'return' в' try' и создавая соответствующий журнал блокировки catch, исключение и return 'null' должно работать (хотя и не обязательно самое приятное). –

+0

Он отлично работал, спасибо вам большое! Не могли бы вы назвать этот вопрос? В конце концов, я не видел много таких вопросов, и я знаю, что многие другие могут найти это полезным. –

Смежные вопросы