2015-07-03 68 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 .... –

相关问题