We can use FXML to separate Java code and the visual design. It also leads to this minimal code in the main Java file.
This is the main Java file. It will load the FXML document, FXMLDocument.fxml, in this case.
package ex43;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Ex43 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass()
.getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Example 43. FXML");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This is the FXML document. It contains the name of the Java controller class, FXMLDocumentController, in the package ex43. We can use SceneBuilder to write this document.
<?import javafx.geometry.Insets?>
<?import javafx.scene.Group?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>
<Group id="Group" xmlns="http://javafx.com/javafx/8.0.60"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="ex43.FXMLDocumentController">
<children>
<VBox alignment="CENTER" prefHeight="400.0" prefWidth="400.0"
spacing="50.0">
<children>
<HBox prefHeight="400.0" prefWidth="400.0" spacing="50.0">
<children>
<Button onAction="#handleButtonAction1" text="Dec Count">
<font>
<Font size="18.0" />
</font></Button>
<Button onAction="#handleButtonAction2" text="Inc Count">
<font> <Font size="18.0" /> </font></Button>
</children>
</HBox>
<Label fx:id="label1" text="Count: 0">
<font>
<Font size="18.0" />
</font></Label>
<Label fx:id="label2" text="Even">
<font>
<Font size="18.0" />
</font></Label>
</children>
<padding>
<Insets bottom="50.0" left="50.0" right="50.0" top="50.0" />
</padding>
</VBox>
</children>
</Group>
This is FXMLDocumentController.java. It contains reference to ids from FXML doc, for label1 and label2.
package ex43;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class FXMLDocumentController implements Initializable {
@FXML
private Label label1, label2;
private int count;
private String oddEven;
@FXML
private void handleButtonAction1(ActionEvent event) {
count--;
displayCount();
}
@FXML
private void handleButtonAction2(ActionEvent event) {
count++;
displayCount();
}
@Override
public void initialize(URL url, ResourceBundle rb) {
}
private void displayCount(){
label1.setText("Count: " + count);
if (count%2==0) oddEven = "Even";
else oddEven = "Odd";
label2.setText(oddEven);
}
}
This is the output:
No comments:
Post a Comment