AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79245585
Accepted
Adalberto J. Brasaca
Adalberto J. Brasaca
Asked: 2024-12-03 04:58:15 +0800 CST2024-12-03 04:58:15 +0800 CST 2024-12-03 04:58:15 +0800 CST

JavaFX - 在节点创建时更新进度条

  • 772

我在平台上看到了很多关于使用线程更新 ProgressBar 的代码,但所有这些都与执行某些计算或更新某些控件属性有关。我不知道这是否可行,但我需要的是 ProgressBar 显示创建 225 (15 X 15) 到 2500 (50 x 50) 个 TextField 的进度。以下是文件和 .fxml。当我包含线程代码部分时,网格停止出现。提前谢谢您。

应用程序

在此处输入图片描述

网格应用程序.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class GridCenterApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(GridCenterApplication.class.getResource("main-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load());
        stage.setTitle("Grid");
        stage.setScene(scene);
        stage.setMaximized(true);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

网格控制器.java

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;

import java.net.URL;
import java.util.ResourceBundle;

public class GridCenterController implements Initializable {

    @FXML
    private ScrollPane scpGrid;

    @FXML
    private Spinner<Integer> spnCols;

    @FXML
    private Spinner<Integer> spnRows;

    @FXML
    private ProgressBar pgbProgress;

    GridPane gridPane;

    private final int CELL_HORIZONTAL_GAP = 1;
    private final int CELL_VERTICAL_GAP = 1;
    private final int CELL_HORIZONTAL_SIZE = 40;
    private final int CELL_VERTICAL_SIZE = 40;

    private int totalCols = 0;
    private int totalRows = 0;

    @FXML
    void onMnuItemNewGridAction(ActionEvent event) {

        if(!(scpGrid.getContent() == null)){
            scpGrid.setContent(null);
        }

        totalCols = spnCols.getValue();
        totalRows = spnRows.getValue();

        var newGrid = new Grid(totalCols, totalRows, CELL_HORIZONTAL_GAP, CELL_VERTICAL_GAP, CELL_HORIZONTAL_SIZE,
                CELL_VERTICAL_SIZE, pgbProgress);
        gridPane = newGrid.getGrid();
        scpGrid.setContent(gridPane);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        SpinnerValueFactory<Integer> numberOfCols = new SpinnerValueFactory.IntegerSpinnerValueFactory(15, 50);
        SpinnerValueFactory<Integer> numberOfRows = new SpinnerValueFactory.IntegerSpinnerValueFactory(15, 50);
        spnCols.setValueFactory(numberOfCols);
        spnRows.setValueFactory(numberOfRows);
        scpGrid.contentProperty().addListener((observableValue, oldValue, newValue) -> {
            if (newValue != null && newValue.isVisible()) {
               pgbProgress.setProgress(0);
            }
        });

    }
}

网格.java

import javafx.concurrent.Task;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

public class Grid {

    private final GridPane grid;

    public Grid(int totalCols, int totalRows, int CELL_HORIZONTAL_GAP, int CELL_VERTICAL_GAP, int CELL_HORIZONTAL_SIZE,
                int CELL_VERTICAL_SIZE, ProgressBar pgbProgress) {

        grid = new GridPane();
        grid.setHgap(CELL_HORIZONTAL_GAP);
        grid.setVgap(CELL_VERTICAL_GAP);
        TextField[][] arrayLetterField = new TextField[totalCols][totalRows];

        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {

                pgbProgress.setProgress(0);
                double total = totalCols * totalRows;
                double i = 1.0;

                for (int row = 0; row < totalRows; row++) {
                    for (int col = 0; col < totalCols; col++) {
                        arrayLetterField[col][row] = new TextField();
                        arrayLetterField[col][row].setMinSize(CELL_HORIZONTAL_SIZE, CELL_VERTICAL_SIZE);
                        arrayLetterField[col][row].setMaxSize(CELL_HORIZONTAL_SIZE, CELL_VERTICAL_SIZE );
                        grid.add(arrayLetterField[col][row], col, row);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        updateProgress(i, total);
                        i++;
                    }
                }
                return null;
            }
        };

        pgbProgress.progressProperty().bind(task.progressProperty());
        new Thread(task).start();

    }

    public GridPane getGrid() {
        return grid;
    }

}

主视图.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.ProgressBar?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.Spinner?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>

<BorderPane prefHeight="767.0" prefWidth="1053.0" xmlns="http://javafx.com/javafx/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.gridpanetest.GridCenterController">
    <top>
        <VBox prefWidth="100.0" BorderPane.alignment="CENTER">
            <children>
                <MenuBar fx:id="mnuBar" prefHeight="25.0" prefWidth="360.0">
                    <menus>
                        <Menu mnemonicParsing="false" text="Grid">
                            <items>
                                <MenuItem mnemonicParsing="false" onAction="#onMnuItemNewGridAction" text="New grid" />
                            </items>
                        </Menu>
                    </menus>
                </MenuBar>
            <Pane prefHeight="80.0" prefWidth="1053.0">
               <children>
                  <Label layoutX="26.0" layoutY="15.0" text="Columns" />
                  <Label layoutX="26.0" layoutY="46.0" text="Rows" />
                  <Spinner fx:id="spnCols" layoutX="79.0" layoutY="11.0" prefHeight="25.0" prefWidth="57.0" />
                  <Spinner fx:id="spnRows" layoutX="79.0" layoutY="42.0" prefHeight="25.0" prefWidth="57.0" />
                  <ProgressBar fx:id="pgbProgress" focusTraversable="false" layoutX="185.0" layoutY="31.0" prefWidth="200.0" progress="0.0" />
               </children>
            </Pane>
            </children>
        </VBox>
    </top>
   <center>
        <ScrollPane fx:id="scpGrid" style="-fx-background-color: #dbbb92; -fx-background: #dbbb92;" BorderPane.alignment="CENTER" />
   </center>
</BorderPane>
multithreading
  • 1 1 个回答
  • 31 Views

1 个回答

  • Voted
  1. Best Answer
    Sai Dandem
    2024-12-03T08:35:09+08:002024-12-03T08:35:09+08:00

    我认为代码中的主要问题在于向网格添加文本字段的部分。这是因为您尝试在不同的线程中添加子节点,而不是在 JavaFX 线程中添加。

    一个快速修复方法是将该代码包装在 Platform.runLater 中,如下所示:

    int c = col;
    int r = row;
    Platform.runLater(() -> grid.add(arrayLetterField[c][r], c, r));
    

    但这不会是您想要的行为,因为您添加网格太早,所以您会看到节点一个接一个地添加。

    要在最后更新 scrollPane,您可以尝试以下代码来获得所需的行为。我还包含了即时更新节点的逻辑,仅供参考,让您有一些想法。

    在此处输入图片描述

    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.concurrent.Task;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.Priority;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    public class NodesProgressBarDemo extends Application {
        @Override
        public void start(Stage primaryStage) throws Exception {
            TextField cols = new TextField();
            cols.setPrefWidth(100);
            TextField rows = new TextField();
            rows.setPrefWidth(100);
            Button generateLazily = new Button("Generate Lazily");
            Button generateInstantly = new Button("Generate Instantly");
            HBox row = new HBox(20, new HBox(10, new Label("Columns:"), cols),
                    new HBox(10, new Label("Rows:"), rows),
                    generateLazily, generateInstantly);
            row.setAlignment(Pos.CENTER_LEFT);
    
            ProgressBar progressBar = new ProgressBar();
            progressBar.setProgress(0);
            progressBar.setMaxWidth(Double.MAX_VALUE);
    
            ScrollPane scrollPane = new ScrollPane();
            scrollPane.setFitToHeight(true);
            scrollPane.setFitToWidth(true);
            VBox.setVgrow(scrollPane, Priority.ALWAYS);
    
            generateLazily.setOnAction(e -> updateGridLazily(cols.getText(), rows.getText(), scrollPane, progressBar));
            generateInstantly.setOnAction(e -> updateGridInstantly(cols.getText(), rows.getText(), scrollPane, progressBar));
    
            VBox root = new VBox(10, row, progressBar, scrollPane);
            root.setPadding(new Insets(10));
            Scene scene = new Scene(root, 700, 500);
            primaryStage.setScene(scene);
            primaryStage.setTitle("Nodes ProgressBar Demo");
            primaryStage.show();
        }
    
        private void updateGridLazily(String col, String row, ScrollPane scrollPane, ProgressBar progressBar) {
            int columns = Integer.parseInt(col);
            int rows = Integer.parseInt(row);
    
            ObjectProperty<Node> content = new SimpleObjectProperty<>();
            Task<Void> task = new Task<>() {
                @Override
                protected Void call() {
                    int total = columns * rows;
                    int count = 0;
                    GridPane gridPane = new GridPane();
                    gridPane.setVgap(5);
                    gridPane.setHgap(5);
                    content.set(gridPane);
                    for (int r = 0; r < rows; r++) {
                        for (int c = 0; c < columns; c++) {
                            TextField textField = new TextField();
                            textField.setMinSize(40, 40);
                            textField.setMaxSize(40, 40);
                            gridPane.add(textField, c, r);
    
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
    
                            count++;
                            updateProgress(count, total);
                        }
                    }
                    return null;
                }
            };
            task.setOnSucceeded(e -> {
                scrollPane.setContent(content.get());
                progressBar.setProgress(0);
            });
            task.progressProperty().addListener((obs, old, val) -> progressBar.setProgress(val.doubleValue()));
            new Thread(task).start();
        }
    
        private void updateGridInstantly(String col, String row, ScrollPane scrollPane, ProgressBar progressBar) {
            int columns = Integer.parseInt(col);
            int rows = Integer.parseInt(row);
    
            GridPane gridPane = new GridPane();
            gridPane.setVgap(5);
            gridPane.setHgap(5);
            scrollPane.setContent(gridPane);
    
            Task<Void> task = new Task<>() {
                @Override
                protected Void call() {
                    int total = columns * rows;
                    int count = 0;
                    for (int r = 0; r < rows; r++) {
                        for (int c = 0; c < columns; c++) {
                            TextField textField = new TextField();
                            textField.setMinSize(40, 40);
                            textField.setMaxSize(40, 40);
                            int r1 = r;
                            int c1 = c;
    
                            Platform.runLater(() -> gridPane.add(textField, c1, r1));
    
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
    
                            count++;
                            updateProgress(count, total);
                        }
                    }
                    return null;
                }
            };
            task.setOnSucceeded(e -> progressBar.setProgress(0));
            task.progressProperty().addListener((obs, old, val) -> progressBar.setProgress(val.doubleValue()));
            new Thread(task).start();
        }
    }
    

    相关任务 Javadoc

    • 修改场景图的任务
    • 返回部分结果的任务
    • 3

相关问题

  • JMeter 属性并发写入

  • 如何在生成的 tauri 异步运行时线程中使用托管 Tauri 状态变量?

  • 主线程中额外的 println 导致 Rust 执行不同的结果

  • 从缓存中刷新低争用原子的最佳方式?

  • Rust:遍历文件夹并打开每个文件

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve