Search code examples
javauser-interfacejavafxgridpane

How to set multiple buttons and add them to a gridPane


for a GUI i have to set multiple buttons to a GridPane. For this i want to ask if there is a way to add multiple buttons in a Grid in a more elegant way than i do. Here is an extractof my Code.

Button button0 =new Button("0");
    Button button1 =new Button("1");
    Button button2 =new Button("2");
    Button button3 =new Button("3");
    Button button4 =new Button("4");
    Button button5 =new Button("5");
    Button button6 =new Button("6");
    Button button7 =new Button("7");
    Button button8 =new Button("8");
    Button button9 =new Button("9");
    Button cancel = new Button("C");
    Button plus = new Button("+");
    Button minus = new Button("-");
    Button multiplicate = new Button("*");
    Button divide = new Button("/");
    Button equal = new Button("=");

For all of those buttons i have to set the row and column index separately.

root.setPadding(new Insets(5,5,5,5));
    GridPane.setConstraints(root, 4, 3);
    root.getChildren();
    root.add(label, 1, 1, 3, 1);
    root.add(button1, 2, 2);
    root.add(button2, 3, 2);
    root.add(button3, 4, 2);
    root.add(button4, 2, 3);
    root.add(button5, 3, 3);
    root.add(button6, 4, 3);
    root.add(button7, 2, 4);
    root.add(button8, 3, 4);
    root.add(button9, 4, 4);
    root.add(button0, 2, 5);
    root.add(cancel, 3, 5);
    root.add(plus, 5,2);
    root.add(minus, 5,3);
    root.add(multiplicate, 5, 4);
    root.add(divide, 5,5);
    root.add(equal, 4, 5);

I would be very greateful for any suggestions.


Solution

  • public class MainController implements Initializable {
    
        int z1=0,y2=0,x=0; 
    
        @FXML
        GridPane gp;
    
        public void initialize(URL arg0, ResourceBundle arg1) {
            // TODO Auto-generated method stub
            while(z1<4){    //add 4 buttons
                addButton();
                z1++;
            }   
        }   
    
        private void addButton() {
            // TODO Auto-generated method stub
            final Button temp1=new Button("Button "+ y2);
            final int numberButton=y2;
            temp1.setId(""+y2);
            temp1.setText("whatever u want!!");
            temp1.setOnAction(new EventHandler<ActionEvent>() {
    
                @Override
                public void handle(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    System.out.println("id("+temp1.getId()+")="+numberButton);
                }
            });
            gp.add(temp1, x, 0);  //x is column index and 0 is row index
            x++;
        }
    }