У меня проблема с изменением сцен в моем приложении, которое выглядит как
Main screen > Login screenЯ храню экраны в главном файле как hashmap<String, Node> и все хорошо, пока я не вернусь с экрана входа на главный экран и не захочу снова загрузить экран входа, вот исключение и код:
java.lang.IllegalArgumentException: [email protected][styleClass=root]is already set as root of another scene
public static final HashMap<String, Parent> pages = new HashMap<>();
@FXML
private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Stage stage = (Stage) button.getScene().getWindow(); if(stage.getScene() != null) {stage.setScene(null);} Parent root = MyApplication.pages.get("LoginPage"); Scene scene = new Scene(root, button.getScene().getWidth(), button.getScene().getHeight()); stage.setScene(scene);
}Это работает, когда я создаю новую опорную панель
Parent root = new AnchorPane(MyApplication.pages.get("LoginPage"));Но я хочу понять, почему это дает мне исключение, если я работаю на одной сцене
#javafx #незаконное исключение аргумента
Вопрос:
У меня проблема с изменением сцен в моем приложении, которое выглядит так
Main screen gt; Login screen Я сохраняю экраны в главном файле как hashmaplt;String, Nodegt; и все хорошо, пока я не вернусь с экрана входа на главный экран и не захочу снова загрузить экран входа, вот исключение и код:
java.lang.IllegalArgumentException: AnchorPane@30561c33[styleClass=root]is already set as root of another scene public static final HashMaplt;String, Parentgt; pages = new HashMaplt;gt;(); @FXML private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Stage stage = (Stage) button.getScene().getWindow(); if(stage.getScene() != null) {stage.setScene(null);} Parent root = MyApplication.pages.get("LoginPage"); Scene scene = new Scene(root, button.getScene().getWidth(), button.getScene().getHeight()); stage.setScene(scene); } Это работает, когда я создаю новое якорное крепление
Parent root = new AnchorPane(MyApplication.pages.get("LoginPage")); Но я хочу понять, почему это дает мне исключение, если я работаю на одной и той же сцене
Ответ №1:
Исключение довольно понятно: панель привязки не может быть корнем двух разных сцен. Вместо того, чтобы каждый раз создавать новую сцену, просто замените корень существующей сцены:
@FXML private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Scene scene = button.getScene(); Parent root = MyApplication.pages.get("LoginPage"); scene.setRoot(root); } Комментарии:
I’m struggling to get r2d3 + Shiny to render questions uvdos r2d3 just a .png file. I’m able to do it if I use questions uvdos r2d3 an URL in the .js file, but nothing is questions uvdos r2d3 rendered if I use a relative path towards questions uvdos r2d3 the exact same file, but stored locally. questions uvdos r2d3 I’ve of course checked the local file questions uvdos r2d3 exists, that there’s no typo in the path, questions uvdos r2d3 etc.
I’ve built a toy R Shiny app to reproduce questions uvdos r2d3 the problem. It only renders a d3 chart, questions uvdos r2d3 which itself is just displaying the RStudio questions uvdos r2d3 logo in a .png file (comment/uncomment the 2 questions uvdos r2d3 last lines of the .js file to see the questions uvdos r2d3 problem). Why is that happening? How to get questions uvdos r2d3 a local image to be displayed using r2d3? questions uvdos r2d3 I’ve been looking for a solution for hours, questions uvdos r2d3 in vain.
library(r2d3)
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage( # Application title titlePanel("Reprex"), # Sidebar with a slider input for number of bins sidebarLayout( sidebarPanel( ), # Show a plot of the generated distribution mainPanel( d3Output("d3Chart", width = "100%", height = "800px") # d3output is the kind of output needed for D3; it requires renderD3 on the server side ) )
)
# Define server logic required to draw a histogram
server <- function(input, output) { output$d3Chart <- renderD3({ # generate bins based on input$bins from ui.R r2d3(script = "./reprex.js", d3_version ="6") })
}
# Run the application
shinyApp(ui = ui, server = server)svg .append("image") .attr("class","expand") .attr("x", 0) .attr("y", 0) .attr('width', 50) .attr('height', 50) .style("opacity",1) .attr("xlink:href", "https://www.rstudio.com/wp-content/uploads/2018/10/RStudio-Logo.png"); // It works with that image but NOT with a local image. Why? //.attr("xlink:href", "./RStudio-Logo.png");I’m using R-4.1.2 + RStudio 1.4.1717 to run questions uvdos r2d3 the Shiny app.
I am building a simple JavaFX application that requires me to launch a modal window in front of my main application window. Using the code below, I am able to launch the modal window 1 time and close it. If I attempt to launch it again, I receive:
java.lang.IllegalArgumentException: BorderPane[id=root, styleClass=root]is already set as root of another sceneI am using the Spring Controller/FXML View dependency injection method described here:
http://www.zenjava.com/2012/02/20/porting-first-contact-to-spring/
I am able to programatically create a scene and hide/display a simple dialog without using FXML / Spring Controller injection. This works fine.
I am unable to explain the ‘already set as root’ exception, as I am creating a new Scene() each time the startButton is clicked. The 1st Scene should have been destroyed whenever the modal window was closed the 1st time.
Relevant files are below.
MainTabPanel.java – The main view of my application. This contains the ‘startButton’ that is clicked to launch the modal window.
Below is the initialize() method that attempts to launch the modal when startButton is clicked.
@FXML public void initialize() { availableReceiversIdColumn.setCellValueFactory(new PropertyValueFactory("id")); availableReceiversFirmwareVersionColumn.setCellValueFactory(new PropertyValueFactory("firmwareVersion")); availableReceiversModelColumn.setCellValueFactory(new PropertyValueFactory("model")); availableReceiversChannelColumn.setCellValueFactory(new PropertyValueFactory("channel")); ObservableList<String> responseTypes = FXCollections.observableArrayList(); responseTypes.add("Single Response Alpha"); responseTypes.add("Single Response Numeric"); responseTypeChoiceBox.setItems(responseTypes); startButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); presentationResponseService.startPresentation(); activePresentation.populateResponses(null); activePresentation.populateResults(null); Scene activePresentationScene = new Scene(activePresentation.getView()); activePresentationScene.getStylesheets().add("styles.css"); stage.setScene(activePresentationScene); stage.setTitle("Active Presentation"); stage.showAndWait(); } }); }closeButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { presentationResponseService.closePresentation(); Stage stage = (Stage) root.getScene().getWindow(); stage.close(); } });@Bean public ActivePresentation activePresentation() { return loadPresenter("/fxml/ActivePresentation.fxml"); }private <T> T loadPresenter(String fxmlFile) { try { FXMLLoader loader = new FXMLLoader(); loader.load(getClass().getResourceAsStream(fxmlFile)); return (T) loader.getController(); } catch (IOException e) { throw new RuntimeException(String.format("Unable to load FXML file '%s'", fxmlFile), e); } }Я создаю простое приложение JavaFX, которое требует от меня запуска модального окна перед моим основным окном приложения. Используя приведенный ниже код, я могу запустить модальное окно 1 раз и закрыть его. Если я попытаюсь запустить его снова, я получу:
java.lang.IllegalArgumentException: BorderPane[id=root, styleClass=root]is already set as root of another sceneЯ использую метод внедрения зависимостей Spring Controller/FXML View, описанный здесь: http://www.zenjava.com/2012/02/20/porting-first-contact-to-spring/
Я могу программно создать сцену и скрыть / отобразить простой диалог без использования FXML / Spring Controller. Это отлично работает.
Я не могу объяснить исключение «уже установлено как root», так как я создаю новую функцию Scene() при каждом нажатии кнопки startButton. Первая сцена должна была быть уничтожена всякий раз, когда модальное окно было закрыто в первый раз.
Соответствующие файлы ниже.
MainTabPanel.java — основной вид моего приложения. Это содержит ‘startButton’, который нажимается для запуска модального окна.
Ниже приведен метод initialize(), который пытается запустить модальный режим при нажатии кнопки startButton.
@FXML public void initialize() { availableReceiversIdColumn.setCellValueFactory(new PropertyValueFactory("id")); availableReceiversFirmwareVersionColumn.setCellValueFactory(new PropertyValueFactory("firmwareVersion")); availableReceiversModelColumn.setCellValueFactory(new PropertyValueFactory("model")); availableReceiversChannelColumn.setCellValueFactory(new PropertyValueFactory("channel")); ObservableList<String> responseTypes = FXCollections.observableArrayList(); responseTypes.add("Single Response Alpha"); responseTypes.add("Single Response Numeric"); responseTypeChoiceBox.setItems(responseTypes); startButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Stage stage = new Stage(); stage.initModality(Modality.APPLICATION_MODAL); presentationResponseService.startPresentation(); activePresentation.populateResponses(null); activePresentation.populateResults(null); Scene activePresentationScene = new Scene(activePresentation.getView()); activePresentationScene.getStylesheets().add("styles.css"); stage.setScene(activePresentationScene); stage.setTitle("Active Presentation"); stage.showAndWait(); } }); }CloseButton определяется в модальном диалоге следующим образом.
closeButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { presentationResponseService.closePresentation(); Stage stage = (Stage) root.getScene().getWindow(); stage.close(); } });Java-конфигурация Spring для bean-компонента ActivePresentation и загрузчика FXML выглядит следующим образом.
@Bean public ActivePresentation activePresentation() { return loadPresenter("/fxml/ActivePresentation.fxml"); }private <T> T loadPresenter(String fxmlFile) { try { FXMLLoader loader = new FXMLLoader(); loader.load(getClass().getResourceAsStream(fxmlFile)); return (T) loader.getController(); } catch (IOException e) { throw new RuntimeException(String.format("Unable to load FXML file '%s'", fxmlFile), e); } }Я хотел сделать кнопку, чтобы перезапустить небольшую игру, которую я сделал (в игре вы должны поднять монету и добраться до выхода, пока змея пытается вас убить), но теперь я получаю это исключение:
Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: [email protected][styleClass=root]is already set as root of another scene at javafx.scene.Scene$9.invalidated(Scene.java:1110) at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:111) at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146) at javafx.scene.Scene.setRoot(Scene.java:1072) at javafx.scene.Scene.<init>(Scene.java:347) at javafx.scene.Scene.<init>(Scene.java:194) at application.Main.startGame(Main.java:216) at application.Main.start(Main.java:307) at application.Main.restart(Main.java:298) at application.Main.lambda$2(Main.java:276) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Node.fireEvent(Node.java:8411) at javafx.scene.control.Button.fire(Button.java:185) at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96) at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89) at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218) at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238) at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191) at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56) at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114) at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74) at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54) at javafx.event.Event.fireEvent(Event.java:198) at javafx.scene.Scene$MouseHandler.process(Scene.java:3757) at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485) at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762) at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394) at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:432) at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:410) at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431) at com.sun.glass.ui.View.handleMouseEvent(View.java:555) at com.sun.glass.ui.View.notifyMouse(View.java:937) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186) at java.lang.Thread.run(Unknown Source)Я догадывался, что проблема в кнопке, но, судя по всему, проблема во всей панели. Вот код, который может вызвать эту проблему:
public class Main extends Application { private Pane root = new Pane(); private static Button btnNewGame = new Button( "New Game?" ); private Parent createContent() { root.setPrefSize( 1280, 720 ); timer.start(); return root; } void cleanup() { timer.stop(); root.getChildren().clear(); } public void startGame( Stage stage ) { Scene scene = new Scene( createContent() ); btnNewGame.setOnAction( e -> { restart( stage ); }); stage.setScene( scene ); stage.setTitle( "ZZZZZnake - Von Christoph Gabauer" ); stage.getIcons().add( new Image( Main.class.getResourceAsStream( "icon.png" ) ) ); stage.setResizable( false ); stage.show(); } void restart( Stage stage ) { cleanup(); start( stage ); timer.start(); } @Override public void start( Stage primaryStage ) { startGame( primaryStage ); }
}Надеюсь, вы можете мне помочь, и заранее спасибо.
С наилучшими пожеланиями из Баварии
Of javafx IllegalArgumentException (is already set as root of another scene)
The exception is pretty issuse uvdos illegalargumentexception self-explanatory: the anchor pane cannot issuse uvdos illegalargumentexception be the root of two different scenes. issuse uvdos illegalargumentexception Instead of creating a new scene every issuse uvdos illegalargumentexception time, just replace the root of the issuse uvdos illegalargumentexception existing scene:
@FXML
private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Scene scene = button.getScene(); Parent root = MyApplication.pages.get("LoginPage"); scene.setRoot(root);
}Answer Link
Ответ
Исключение довольно очевидно: панель привязки не может быть корнем двух разных сцен. Вместо того, чтобы каждый раз создавать новую сцену, просто замените корень существующей сцены:
@FXML
private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Scene scene = button.getScene(); Parent root = MyApplication.pages.get("LoginPage"); scene.setRoot(root);
}Javafx IllegalArgumentException (is already set as root of another scene)
I have problem with changing scenes in my post uvdos illegalargumentexception application which looks like
Main screen > Login screenI am storing screens in main file as post uvdos illegalargumentexception hashmap<String, Node> and everything post uvdos illegalargumentexception is good until I go back from login screen to post uvdos illegalargumentexception main screen and want to load the login post uvdos illegalargumentexception screen again, here is exception and code:
java.lang.IllegalArgumentException: AnchorPane@30561c33[styleClass=root]is already set as root of another scene
public static final HashMap<String, Parent> pages = new HashMap<>();
@FXML
private void LogIn(ActionEvent event) { Button button = (Button) event.getSource(); Stage stage = (Stage) button.getScene().getWindow(); if(stage.getScene() != null) {stage.setScene(null);} Parent root = MyApplication.pages.get("LoginPage"); Scene scene = new Scene(root, button.getScene().getWidth(), button.getScene().getHeight()); stage.setScene(scene);
}It works when I’m creating new anchorpane
Parent root = new AnchorPane(MyApplication.pages.get("LoginPage"));But I want to understand why it gives me an post uvdos illegalargumentexception exception if I’m working on the same stage
Total Answers 1
Cant render a local image in D3, despite being able to render one using an URL
Thanks to Geovany, this was solved. I blogs uvdos r added in app.R, before the ui function, blogs uvdos r addResourcePath(«images», «.») , so that blogs uvdos r I can access the working directory my blogs uvdos r picture is stored in (here, where app.R blogs uvdos r is located) using the tag images. By blogs uvdos r replacing the last line of reprex.js blogs uvdos r with .attr(«xlink:href», blogs uvdos r «images/RStudio-Logo.png»); (and letting blogs uvdos r the previous line commented), the blogs uvdos r picture was displayed.
Answer Link






