JavaFX2 - very poor performance when adding custom made (fxml)panels to gridpane dynamically

前端 未结 3 1094
心在旅途
心在旅途 2020-12-28 22:39

Problem I want to add custom made panels, built via javafx scene builder, to a gridpane at runtime. My custom made panel exsits of buttons, labels and so on

3条回答
  •  鱼传尺愫
    2020-12-28 23:12

    I have had a similar issue. I also had to load a custom fxml-based component several times, dynamically, and it was taking too long. The FXMLLoader.load method call was expensive, in my case.

    My approach was to parallelize the component instantiation and it solved the problem.

    Considering the example posted on the question, the controller method with multithread approach would be:

    private void textChange(KeyEvent event) {
        GridPane g = new GridPane();
        // creates a thread pool with 10 threads
        ExecutorService threadPool = Executors.newFixedThreadPool(10); 
        final List listOfComponents = Collections.synchronizedList(new ArrayList(100));
    
        for (int i = 0; i < 100; i++) {
            // parallelizes component loading
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    listOfComponents.add(new Celli());
                }
            });
        }
    
        // waits until all threads completion
        try {
            threadPool.shutdown();      
            threadPool.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // seems to be a improbable exception, but we have to deal with it
            e.printStackTrace();
        }
    
        g.getChildren().addAll(listOfComponents);
    }
    

提交回复
热议问题