【发布时间】:2015-02-24 09:39:34
【问题描述】:
假设我有一个带有按钮的窗口。每次按下该按钮时,我都希望处理当前窗口并显示一个新窗口。
在 Swing 中,这很容易,但我在 JavaFx 中找不到它的语法? 那么在这种情况下,使用我的示例代码,我该怎么做呢?
public class Main extends Application {
Parent root;
Scene scene;
@Override
public void start(Stage primaryStage) throws Exception {
root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.sizeToScene();
primaryStage.setResizable(false);
primaryStage.show();
root.setOnMouseClicked((MouseEvent mouseEvent) -> {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
Stage stage = new Stage();
stage.setScene(primaryStage.getScene());
stage.show();
primaryStage.close();
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
尝试创建新窗口:http://sv.tinypic.com/r/1jkq4w/8
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<VBox prefHeight="430.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="blackjack.FXMLDocumentController">
<children>
<AnchorPane maxHeight="-1.0" maxWidth="-1.0" prefHeight="-1.0" prefWidth="-1.0" VBox.vgrow="ALWAYS">
<children>
<Label fx:id="labelPlayerTotal" layoutX="510.0" layoutY="335.0" prefHeight="15.0" prefWidth="121.0" text="Playertotal:" />
<Label fx:id="labelDealerTotal" layoutX="510.0" layoutY="359.0" prefHeight="15.0" prefWidth="112.0" text="Dealertotal:" />
<TextArea fx:id="dealerArea" layoutY="29.0" prefHeight="159.0" prefWidth="503.0" />
<TextArea fx:id="playerArea" layoutY="244.0" prefHeight="159.0" prefWidth="503.0" />
<Button fx:id="stayButton" layoutX="512.0" layoutY="173.0" mnemonicParsing="false" onAction="#drawCardForDealer" prefHeight="25.0" prefWidth="72.0" text="STAY" />
<Button fx:id="hitButton" layoutX="512.0" layoutY="130.0" mnemonicParsing="false" onAction="#drawCardForPlayer" prefHeight="25.0" prefWidth="72.0" text="HIT" />
<Label fx:id="labelWinner" layoutX="104.0" layoutY="208.0" prefHeight="15.0" prefWidth="296.0" />
<MenuBar fx:id="helpBar">
<menus>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" onAction="#aboutApplication" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
</children>
</VBox>
【问题讨论】:
-
您是否需要处理窗口或只处理当前的 fxml 也适合您?
-
"..每次按下该按钮时,我都希望释放当前窗口并显示一个新窗口。在 Swing 中,这很简单,.." 简单也许,但不推荐。请参阅The Use of Multiple JFrames, Good/Bad Practice? 如果 Java-FX 将开发人员限制在一个单一的“框架”中,那么它必须是有利于它的东西。
-
@AndrewThompson 谢谢安德鲁,我的 JavaFX 应用程序中需要这个重启按钮,这对我的应用程序来说非常必要。这可能吗?
-
你在 Swing 中使用什么来重启应用程序?
-
@ItachiUchiha "this.dispose(处理当前窗口),new Window().setVisible(true);" .. 如果我没记错语法。