2017-09-23 24 views
0

我想顯示9個按鈕使用javafx。如何使新的按鈕對象使用for循環,並使用javafx顯示

public class Main extends Application 
{ 
    public void start(Stage primaryStage) throws Exception 
    { 

     Button[] button = new Button[10]; 
     Pane pane = new Pane(); 

     for(int i=0; i < 9; i++) 
     { 
      button[i].setText("hi"); 
      button[i].setText("hi"); 
      button[i].setLayoutX(i*10); 

      System.out.println(button[i].getText()); 
      pane.getChildren().addAll(button[i]);     
     } 

     Scene scene = new Scene(pane); 
     primaryStage.setScene(scene); 
     primaryStage.show();  


} 
+1

按鈕應該如何定位? Button應該對他們說些什麼,能給我們更多的細節嗎? –

回答

2

您創建一個array能夠存儲Button元素,但你永遠不那麼創建Button本身

你要做的:

for(int i=0; i < 9; i++){ 
    button[i] = new Button();  // <-- here 
    button[i].setText("hi");  // you have twice this line 
    button[i].setLayoutX(i*10); 

    System.out.println(button[i].getText()); 
    pane.getChildren().addAll(button[i]);     
} 

而且,如果其他部分你以後不需要檢索button,你不需要如此存儲它們並使用array,這將工作:

for(int i=0; i < 9; i++){ 
    Button btn = new Button();  // <-- here 
    btn.setText("hi"); 
    btn.setLayoutX(i*10); 

    System.out.println(btn.getText()); 
    pane.getChildren().addAll(btn);     
}