Noa*_*oah 5 java javafx internationalization
我编写了这个应用程序来测试国际化:
主.java:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader();
loader.setResources(ResourceBundle.getBundle("content", Locale.ENGLISH));
Parent root = loader.load(getClass().getResource("sample.fxml").openStream());
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
示例.fxml:
<AnchorPane prefHeight="400.0" prefWidth="600.0" >
<children>
<Label layoutX="10.0" layoutY="10.0" text="%label" />
</children>
</AnchorPane>
Run Code Online (Sandbox Code Playgroud)
content_en.properties:
label=Hello World
Run Code Online (Sandbox Code Playgroud)
但是我不能在我的应用程序中使用 FXML。没有 FXML 我怎么能做到这一点?
如果我只是添加一个标签并将其文本设置为%label
它不起作用。
FXMLLoader
处理以%
.开头的文本。如果您不打算使用FXML
,您可以获得这样的国际化文本:
ResourceBundle rb = ResourceBundle.getBundle("content");
Label label = new Label(rb.getString("label"));
Run Code Online (Sandbox Code Playgroud)
如果你想在ResourceBundle
任何地方使用相同的,你可以创建一个带有静态方法的类来返回国际化的文本值:
public class I18N {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("content");
public static String getString(String key) {
return RESOURCE_BUNDLE.getString(key);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
public class I18N {
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("content");
public static String getString(String key) {
return RESOURCE_BUNDLE.getString(key);
}
}
Run Code Online (Sandbox Code Playgroud)