我有两个JavaFX类,DialogPane.java和Main.java。代码如下:
DialogPane
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中我使用字符串&#34; string&#34;我想在其他课堂上使用。我的意思是,当我按下okbutton时,字符串初始化为&#34; ok&#34;,我想在Main类中使用&#34; ok。怎么做?
答案 0 :(得分:1)
而不是扩展Dialog的类,只需创建一个创建对话框然后返回字符串的方法。
像这样。
public class DialogPane(){
public static string our_return;
public static string createDialog(){
Dialog dialog=new Dialog();
/*Create your dialog from here and add your buttons and so on*/
//then set our_return string using your button
if ((dialog.result.get()) == okbutton) {
our_string ="ok";
}
return our_return;
}
}
然后在你的主要
test.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
String finestra =DialogPane.createDialog();
}
});