search
HomeJavajavaTutorialHow to use JavaFX to implement multi-language supported graphical interface in Java 9

How to use JavaFX in Java 9 to implement a graphical interface with multi-language support

Introduction:
With the development of globalization, multi-language support has become an important requirement for software development. Internationalizing text in different languages ​​is a necessary step when developing graphical interfaces. In Java 9, we can use JavaFX to implement a graphical interface with multi-language support. This article will introduce how to use the Resource Bundle mechanism provided by JavaFX to achieve multi-language support, and give corresponding sample code.

1. Prepare resource files
In the project, we need to prepare a resource file for each language and achieve multi-language support by loading different resource files.

1. Create a resource folder
In the src/main/java directory of the project, create a folder named resources. This folder will be used to store resource files in different languages.

2. Create resource files
In the resources folder, create a resource file for each language. The naming rule of resource files is baseName_language.properties, where baseName is the basic name of the resource file and language is the identifier of the language. For example, we can create a resource file named bundle_zh_CN.properties to store simplified Chinese text.

3. Fill in the resource content
Open the resource file and fill in the text that needs to be internationalized according to the key-value pair. For example, we can add the following content to the bundle_zh_CN.properties file:

greeting=你好!

2. Load resource files
In JavaFX, use the ResourceBundle class to load resource files. We need to select the corresponding resource file according to the user's language in the program to load.

1. Get the default Locale
Locale is a class that describes language, country and other information. We can use the java.util.Locale.getDefault() method to get the current user's default Locale.

2. Load resource files according to Locale
Use the ResourceBundle.getBundle() method to load the corresponding resource file, and the incoming parameters are the basic name and Locale of the resource file. For example, we can load the bundle_zh_CN.properties file through the following code:

ResourceBundle bundle = ResourceBundle.getBundle("bundle", Locale.CHINA);

3. Obtain text content
After we load the resource file, we can obtain the corresponding text based on the key in the resource file content.

1. Obtain text content in JavaFX
In JavaFX, we can achieve text internationalization by annotating @FxText. We need to use this annotation in the FXML file and set the corresponding key. For example, we can write this in the FXML file:

<Text fx:id="greeting" text="%greeting" />

2. Set text content
In the JavaFX controller class, we can get the text content by calling the getString() method of ResourceBundle, and Apply it to the corresponding control. For example, we can write this in the initialization method of the controller class:

@FXML
private Text greeting;
bundle = ResourceBundle.getBundle("bundle", Locale.getDefault());
String greetingText = bundle.getString("greeting");
greeting.setText(greetingText);

4. Switching languages ​​
In order to achieve multi-language support, we need to provide users with the ability to switch languages. We can implement language switching through the trigger events provided by JavaFX.

1. Binding events
In the JavaFX controller class, we can bind a trigger event to the button or menu item that switches languages. For example, we can bind a click event to a button named changeLanguageButton:

<Button fx:id="changeLanguageButton" onAction="#changeLanguageButtonClicked" />

2. Processing events
In the controller class, implement the method to handle the click event. In this method, we need to change the current Locale, reload the resource file, and update the interface. For example, we can implement the changeLanguageButtonClicked() method like this:

@FXML
private void changeLanguageButtonClicked() {
    if (Locale.getDefault().equals(Locale.CHINA)) {
        Locale.setDefault(Locale.US);
    } else {
        Locale.setDefault(Locale.CHINA);
    }
    bundle = ResourceBundle.getBundle("bundle", Locale.getDefault());
    String greetingText = bundle.getString("greeting");
    greeting.setText(greetingText);
}

Conclusion:
By using the resource bundle mechanism provided by JavaFX, we can easily implement a graphical interface with multi-language support. Through the introduction of this article, I believe that everyone can master the method of using JavaFX to achieve multi-language support in Java 9. I hope this article will be helpful to everyone's study.

Reference code:
Contents in resource files in different languages:
bundle_zh_CN.properties

greeting=你好!

bundle.properties

greeting=Hello!

@FxText used in FXML files Note:

<Text fx:id="greeting" text="%greeting" />

Method for handling click events in the controller class:

@FXML
private void changeLanguageButtonClicked() {
    if (Locale.getDefault().equals(Locale.CHINA)) {
        Locale.setDefault(Locale.US);
    } else {
        Locale.setDefault(Locale.CHINA);
    }
    bundle = ResourceBundle.getBundle("bundle", Locale.getDefault());
    String greetingText = bundle.getString("greeting");
    greeting.setText(greetingText);
}

The above is the detailed content of How to use JavaFX to implement multi-language supported graphical interface in Java 9. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment