【发布时间】:2015-11-10 11:51:01
【问题描述】:
我有两个 JavaFX 类,DialogPane.java 和 Main.java。代码如下:
对话窗格
package application;
import java.util.Optional;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
public class DialogPane extends Dialog {
@SuppressWarnings("null")
public DialogPane(){
String string = null;
initModality(Modality.APPLICATION_MODAL);
// initOwner( primaryStage );
// HBox buttonHb = new HBox(10);
// Button textbtn = new Button("Premi");
// buttonHb.setAlignment(Pos.CENTER);
// buttonHb.getChildren().addAll(textbtn);
// ButtonType buttonTypeOne = new ButtonType("Prova");
// ButtonType loginButtonType = new ButtonType("OK", ButtonData.OK_DONE);
// getDialogPane().getButtonTypes().addAll(buttonTypeOne);
ButtonType okbutton = new ButtonType("OK", ButtonData.OK_DONE);
ButtonType cancelbutton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
getDialogPane().getButtonTypes().addAll(okbutton,cancelbutton);
Optional<ButtonType> result = null;
result = showAndWait();
if ((result.get()) == okbutton) {
string ="ok";
}
}
主要
public class Main extends Application {
// a lot of code that doesn't matter now
Button test = new Button("Test");
HBox testbox = new HBox(40);
test.setAlignment(Pos.TOP_CENTER);
test.setStyle("-fx-font-size: 15pt;");
testbox.getChildren().add(test);
test.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
DialogPane finestra = new DialogPane();
}
});
}
在 DialogPane 中,我使用了我想在其他类中使用的字符串“string”。我的意思是,当我按下 okbutton 时,字符串初始化为“ok”,我想在 Main 类中取“ok”。怎么做?
【问题讨论】:
-
只需在
DialogPane中添加一个方法,该方法返回字符串并在 Main 中调用它 -
如果在对话框关闭后我想要“字符串”?
-
DialogPane构造函数调用showAndWait(),因此构造函数在对话框关闭后才会完成。因此,只需在调用new DialogPane()后立即调用该方法。 (一般来说,如果你不使用showAndWait(),你总是可以给Stage.showingProperty()添加一个监听器,但是因为你使用的是showAndWait(),这很容易。)
标签: button javafx dialog return-value