2015-07-03 66 views
3

對於我正在開發的應用程序,我需要用戶輸入多行數據。確切的數字是可變的,用戶也應該能夠自己添加行。現在我已經用JavaFX對話框工作了,除了添加行時,Dialog沒有相應調整大小。有沒有辦法讓對話框在添加行時自動調整大小?如何在添加內容時自動調整對話框的大小?

下面是一個演示應用程序,帶有一個類似於我想要的對話框的樣本測試應用程序。

package test_dialog; 

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.geometry.Pos; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.ButtonType; 
import javafx.scene.control.Dialog; 
import javafx.scene.control.DialogPane; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.GridPane; 
import javafx.scene.layout.StackPane; 
import javafx.stage.Stage; 

public class Test_Dialog extends Application { 

    class ScalableDialog extends Dialog<String> { 

     int nrRows = 2; 

     public ScalableDialog() { 

      // We are resizable 
      setResizable(true); 

      // Set up the grid pane. 
      GridPane grid = new GridPane(); 
      grid.setHgap(10); 
      grid.setVgap(5); 
      grid.setMaxWidth(Double.MAX_VALUE); 
      grid.setAlignment(Pos.CENTER_LEFT); 

      // Set up dialog pane 
      DialogPane dialogPane = getDialogPane(); 
      dialogPane.setHeaderText(null); 
      dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); 
      dialogPane.setContent(grid); 

      // Create some fields to start with 
      for (int i = 0; i < nrRows; i++) { 
       grid.addRow(i, new TextField("Row: " + i)); 
      } 

      // Add button 
      final Button buttonAdd = new Button("Add Row"); 
      buttonAdd.setOnAction((ActionEvent e) -> { 
       // Move Button to next row 
       GridPane.setRowIndex(buttonAdd, nrRows + 1); 
       // Insert new text field row 
       grid.addRow(nrRows, new TextField("New: " + nrRows++)); 
      }); 
      grid.add(buttonAdd, 0, nrRows); 
     } 
    } 

    @Override 
    public void start(Stage primaryStage) { 
     Button button = new Button(); 
     button.setText("Open Dialog"); 
     button.setOnAction(e -> { 
      new ScalableDialog().showAndWait(); 
     }); 

     StackPane root = new StackPane(); 
     root.getChildren().add(button); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setTitle("Scalable Dialog Test"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     launch(args); 
    } 

} 
+0

不知道框架中的一個簡單方法,但是您正在控制新行的添加,因此在添加行之後,您可以手動調整大小。 –

回答

5

「添加」 按鈕的動作事件處理函數中執行

dialogPane.getScene().getWindow().sizeToScene(); 


Stage.sizeToScene()與Swing的jframe.pack()類似。在底部,對話框被添加到一些(次,次)階段,我們可以通過getScene()。getWindow()來獲得它。

+0

你爲什麼要去現場,小心解釋一下先生? – Elltz

+0

非常好,''dialogPane.getScene()。getWindow()。sizeToScene();'做了訣竅。我發現一旦你添加了更多的屏幕可以顯示的行,就會發生各種奇怪的事情(至少在Mac上),但我希望能夠通過在下面添加滾動窗格來阻止這些行... –

+0

@Elltz done .... –

相關問題