Podstawowe kroki (między innymi) internacjonalizacji aplikacji Java to Locale
lizacja i łączenie zasobów. W JavaFX możesz użyć FXMLLoader#setResources()
do tego celu. Tutaj demo SSCCE, aby to zademonstrować. Kody mają charakter samoopisowy.
Struktura pakietu demonstracyjnego:
bundledemo
|------ BundleDemo.java
|------ MyController.java
|------ MyView.fxml
bundles
|------ MyBundle_en.properties
|------ MyBundle_kg.properties
MyBundle_en.properties
key1=Name Surname
key2=How are you?
MyBundle_kg.properties
key1=Aты Жөнү
key2=Кандайсың?
MyView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.*?>
<BorderPane fx:controller="bundledemo.MyController" xmlns:fx="http://javafx.com/fxml">
<top>
<!-- This label's text will be set by the controller -->
<Label fx:id="lblTextByController"/>
</top>
<center>
<!-- This label's text will be taken from the bundle automatically -->
<Label text="%key2"/>
</center>
</BorderPane>
MyController.java
package bundledemo;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
public class MyController implements Initializable {
@FXML private Label lblTextByController;
private ResourceBundle bundle;
@Override
public void initialize(URL location, ResourceBundle resources) {
bundle = resources;
lblTextByController.setText(bundle.getString("key1"));
}
}
BundleDemo.java
package bundledemo;
public class BundleDemo extends Application {
private Stage stage;
@Override
public void start(Stage primaryStage) {
stage = primaryStage;
Button btnEN = new Button();
btnEN.setText("English");
btnEN.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
loadView(new Locale("en", "EN"));
}
});
Button btnKG = new Button();
btnKG.setText("Kyrgyz");
btnKG.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
loadView(new Locale("kg", "KG"));
}
});
VBox root = new VBox(20);
root.getChildren().add(HBoxBuilder.create().spacing(10).style("-fx-background-color: gray").padding(new Insets(5)).children(btnEN, btnKG).build());
root.getChildren().add(new StackPane());
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
private void loadView(Locale locale) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setResources(ResourceBundle.getBundle("bundles.MyBundle", locale));
Pane pane = (BorderPane) fxmlLoader.load(this.getClass().getResource("MyView.fxml").openStream());
StackPane content = (StackPane) ((VBox) stage.getScene().getRoot()).getChildren().get(1);
content.getChildren().clear();
content.getChildren().add(pane);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Zrzut ekranu: