有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java用标签填充GridPane

我有了这个构造函数,我正试图用标签填充网格窗格。 我碰上了一堵墙,不知道出了什么事。 我需要在一行中创建13个标签

建造商:

public class Labels {
   @FXML
    GridPane gridPane = new GridPane();

    public Labels(String labelname, int columnIndex, int rowIndex) {
        Label label = new Label();
        gridPane.setColumnIndex(label, columnIndex);
        gridPane.setRowIndex(label, rowIndex);
        label.setId(labelname+columnIndex);
        label.setVisible(true);
        label.setText("test");
    }   

}

环路控制器:

for(int i2=0; i2<13; i2++){

        Labels labels = new Labels("label", i2, 3);
 }

共 (2) 个答案

  1. # 1 楼答案

    您没有将Label添加到GridPane。此外,对每个Label使用新的GridPane,并且永远不要在任何地方使用这些GridPane

    public class Labels {
    
        private GridPane gridPane = new GridPane();
    
        public GridPane getGridPane() {
            return gridPane; 
        }
    
        public void addLabel(String labelname, int columnIndex, int rowIndex) {
            Label label = new Label();
            GridPane.setColumnIndex(label, columnIndex);
            GridPane.setRowIndex(label, rowIndex);
            label.setId(labelname+columnIndex);
            label.setText("test");
    
            gridPane.getChildren().add(label);
        }   
    
    }
    
    Labels labels = new Labels();
    
    for(int i2=0; i2<13; i2++){
        labels.addLabel("label", i2, 3);
    }
    
    GridPane gridPane = labels.getGridPane();
    // TODO: display gridPane
    
  2. # 2 楼答案

    (总是发mcve

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.GridPane;
    import javafx.stage.Stage;
    
    public class LabelsRow extends Application {
    
        GridPane gridPane;
    
        @Override
        public void start(Stage primaryStage) {
    
            gridPane = new GridPane();
    
            for(int i2=0; i2<13; i2++){
                new Labels("label "+i2 , i2, 3);
            }
    
            Scene scene = new Scene(gridPane);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public class Labels {
    
            Labels labels;
    
            Labels(String labelname, int columnIndex, int rowIndex) {
                Label label = new Label();
                //gridPane.setColumnIndex(label, columnIndex);
                //gridPane.setRowIndex(label, rowIndex);
                gridPane.add(label, columnIndex, rowIndex);
                label.setId(labelname+columnIndex);
                label.setVisible(true);
                label.setText(labelname);
            }
    
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }