- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Java ResourceBundle
In this tutorial we show how to work with a ResourceBundle
in Java.
A resource bundle is a Java properties file that contains locale-specific data. It is a way of internationalizing Java applications by making the code locale-independent.
Hard-coding locale-specific data is not the way to go. Values such as messages or labels should be placed in a separate file. This way we can handle multiple locales without having to write different code for each locale. It is also convenient for translators because they only work with translatable text and do not look at the programming code.
Resouce bundles are organized into families with a common base name. For instance, if we have a words
base name, words_sk
matches the locale for the Slovak language. The default resource bundle is used if a specific locale is not supported.
Resource bundles also support dialects; for example words_es_AR
is used for Spanish language used in Argentina and words_es_BO
in Bolivia.
ResourceBundle
is an abstract class that has two subclasses: PropertyResourceBundle
and ListResourceBundle
. PropertyResourceBundle
loads the data from a properties file. A properties file is a plain-text file that contains translatable text. Properties files are not part of the Java source code, and they can contain only String values. ListResourceBundle
manages resources with a convenient list; it gets the data from a class file. We can store any locale-specific object in a ListResourceBundle
.
To get the appropriate ResourceBundle
, we invoke the ResourceBundle.getBundle()
method. It is a factory method that looks for a ListResourceBundle
, and if it does not find any, it looks for a PropertyResourceBundle
. A MissingResourceException
is thrown if no resource bundle is found.
Using PropertyResourceBundle
In the first application, we create a simple Java application that uses three resource bundles: default English, German, and Slovak.

We create three properties files and place them into the resources
directory.
words.properties
w1 = Earth w2 = ocean
This is the default properties file; it is typically in English language. We have two words inside the file.
words_de.properties
w1 = Erde w2 = ozean
The words_de.properties
file contains words in German language.
words_sk.properties
w1 = Zem w2 = oceán
The words_de.properties
file contains words in Slovak language.
ResourceBundleEx.java
package com.zetcode; import java.util.Locale; import java.util.ResourceBundle; public class ResourceBundleEx { static public void main(String[] args) { Locale[] locales = { Locale.GERMAN, new Locale("sk", "SK"), Locale.ENGLISH }; System.out.println("w1:"); for (Locale locale : locales) { getWord(locale, "w1"); } System.out.println("w2:"); for (Locale locale : locales) { getWord(locale, "w2"); } } static void getWord(Locale curLoc, String key) { ResourceBundle words = ResourceBundle.getBundle("resources/words", curLoc); String value = words.getString(key); System.out.printf("Locale: %s, Value: %s %n", curLoc.toString(), value); } }
In the code example, we print all the words used in three resource bundles.
Locale[] locales = { Locale.GERMAN, new Locale("sk", "SK"), Locale.ENGLISH };
We have three locales in the example: German, Slovak, and English.
for (Locale locale : locales) { getWord(locale, "w1"); }
We go through the locales and print the words marked with the w1
key.
ResourceBundle words = ResourceBundle.getBundle("resources/words", curLoc);
With the ResourceBundle.getBundle()
method, we get the bundle for the currently used locale. Since we have not created a ListResourceBundle
, the method uses a PropertyResourceBundle
, whis loads the data from a properties file.
String value = words.getString(key); System.out.printf("Locale: %s, Value: %s %n", curLoc.toString(), value);
We get the value and print the locale name, the key, and the value.
w1: Locale: de, Value: Erde Locale: sk_SK, Value: Zem Locale: en, Value: Earth w2: Locale: de, Value: ozean Locale: sk_SK, Value: oceán Locale: en, Value: ocean
This is the output of the example.
Using ListResourceBundle
In the following application, we use the ListResourceBundle
.

We create locale resources for Slovak and Czech languages.
MyResources_sk.java
package com.zetcode.myres; import java.util.ListResourceBundle; public class MyResources_sk extends ListResourceBundle { @Override protected Object[][] getContents() { return resources; } private final Object[][] resources = { { "Capital", "Bratislava" }, { "Area", 49035 }, { "Currency", "EUR" }, }; }
Here we have an implementation of the ListResourceBundle
for the Slovak language. We have to override the getContents()
method. The method returns an array of key/value pairs.
MyResources_cs_CZ.java
package com.zetcode.myres; import java.util.ListResourceBundle; public class MyResources_cs_CZ extends ListResourceBundle { @Override protected Object[][] getContents() { return resources; } private final Object[][] resources = { { "Capital", "Praha" }, { "Area", 78866 }, { "Currency", "CZK" }, }; }
This is the implementation for the Czech language.
ResourceBundleEx2.java
package com.zetcode; import java.util.Locale; import java.util.ResourceBundle; public class ResourceBundleEx2 { public static void main(String[] args) { Locale sk_loc = new Locale("sk", "SK"); ResourceBundle bundle = ResourceBundle.getBundle("com.zetcode.myres.MyResources", sk_loc); System.out.println("Capital: " + bundle.getObject("Capital")); System.out.println("Area: " + bundle.getObject("Area")); System.out.println("Currency: " + bundle.getObject("Currency")); System.out.println(); Locale cz_loc = new Locale("cs", "CZ"); ResourceBundle bundle2 = ResourceBundle.getBundle("com.zetcode.myres.MyResources", cz_loc); System.out.println("Capital: " + bundle2.getObject("Capital")); System.out.println("Area: " + bundle2.getObject("Area")); System.out.println("Currency: " + bundle2.getObject("Currency")); } }
The example prints some geographical data for Slovakia and Czech Republic.
Locale sk_loc = new Locale("sk", "SK"); ResourceBundle bundle = ResourceBundle.getBundle("com.zetcode.myres.MyResources", sk_loc);
With the ResourceBundle.getBundle()
method, we create a resource bundle from a com.zetcode.myres.MyResources_sk.class
.
Capital: Bratislava Area: 49035 Currency: EUR Capital: Praha Area: 78866 Currency: CZK
This is the output of the example.
Swing application
In the third example, we create a simple GUI application using Java Swing. The example enables to dynamically change the language of the UI. The example uses the ListResourceBundle
class. For those who are not familiar with Swing, there is a Java Swing tutorial on ZetCode.
The source code and the images are available at the author's Github repository .
MyResources_sk.java
package com.zetcode.myres; import java.util.ListResourceBundle; import javax.swing.ImageIcon; public class MyResources_sk extends ListResourceBundle { @Override protected Object[][] getContents() { return resources; } private final Object[][] resources = { {"name", "Slovensko"}, {"lang_menu", "Jazyk"}, {"lang_sk", "Slovenčina"}, {"lang_hu", "Maďarčina"}, {"flag", new ImageIcon("src/resources/slovakia.png")}, {"description", "Slovensko je vnútrozemský štát v strednej Európe."} }; }
These are resources for the Slovak language. We have five strings and an ImageIcon
.
MyResources_hu.java
package com.zetcode.myres; import java.util.ListResourceBundle; import javax.swing.ImageIcon; public class MyResources_hu extends ListResourceBundle { @Override protected Object[][] getContents() { return resources; } private final Object[][] resources = { {"name", "Magyarország"}, {"lang_menu", "Nyelv"}, {"lang_sk", "Szlovák"}, {"lang_hu", "Magyar"}, {"flag", new ImageIcon("src/resources/hungary.png")}, {"description", "Magyarország közép-európai ország " + "a Kárpát-medencében."} }; }
These are resources for the Hungarian language.
ResourceBundleEx3.java
package com.zetcode; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Locale; import java.util.ResourceBundle; import javax.swing.ButtonGroup; import javax.swing.GroupLayout; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JRadioButtonMenuItem; import javax.swing.LayoutStyle; /* * Java ResourceBundle tutorial * * This program uses a ResourceBundle in a * Java Swing application. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: August 2016 */ public class ResourceBundleEx3 extends JFrame { private ResourceBundle bundle; private JLabel flag; private JLabel lbl; private JMenu langMenu; private JRadioButtonMenuItem skMenuItem; private JRadioButtonMenuItem huMenuItem; public ResourceBundleEx3() { initUI(); } private void initUI() { createMenuBar(); flag = new JLabel(); lbl = new JLabel(); updateLanguage(new Locale("sk", "SK")); createLayout(lbl, flag); pack(); setTitle(bundle.getString("name")); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void updateLanguage(Locale locale) { bundle = ResourceBundle.getBundle("com.zetcode.myres.MyResources", locale); langMenu.setText(bundle.getString("lang_menu")); skMenuItem.setText(bundle.getString("lang_sk")); huMenuItem.setText(bundle.getString("lang_hu")); flag.setIcon((Icon) bundle.getObject("flag")); lbl.setText(bundle.getString("description")); setTitle(bundle.getString("name")); pack(); } private void createMenuBar() { JMenuBar menubar = new JMenuBar(); langMenu = new JMenu(); langMenu.setMnemonic(KeyEvent.VK_F); ButtonGroup btnGroup = new ButtonGroup(); skMenuItem = new JRadioButtonMenuItem("Slovak", true); btnGroup.add(skMenuItem); skMenuItem.addActionListener((ActionEvent e) -> { updateLanguage(new Locale("sk", "SK")); }); langMenu.add(skMenuItem); huMenuItem = new JRadioButtonMenuItem("Hungarian"); btnGroup.add(huMenuItem); huMenuItem.addActionListener((ActionEvent e) -> { updateLanguage(new Locale("hu", "HU")); }); langMenu.add(huMenuItem); menubar.add(langMenu); setJMenuBar(menubar); } private void createLayout(JComponent... arg) { Container pane = getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createParallelGroup() .addComponent(arg[0]) .addComponent(arg[1]) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(arg[1]) ); } public static void main(String[] args) { EventQueue.invokeLater(() -> { ResourceBundleEx3 ex = new ResourceBundleEx3(); ex.setVisible(true); }); } }
We have a menubar with a menu that contains two radio button menu items. Selecting a radio button menu item changes the language of the application's user interface.
private void updateLanguage(Locale locale) { bundle = ResourceBundle.getBundle("com.zetcode.myres.MyResources", locale); langMenu.setText(bundle.getString("lang_menu")); skMenuItem.setText(bundle.getString("lang_sk")); huMenuItem.setText(bundle.getString("lang_hu")); flag.setIcon((Icon) bundle.getObject("flag")); lbl.setText(bundle.getString("description")); setTitle(bundle.getString("name")); pack(); }
When we select a radio button menu item, the updateLanguage()
method is called. It creates a new ResourceBundle
based on the given locale and updates the menu, radio menu items, image icon, description, and frame title.
skMenuItem.addActionListener((ActionEvent e) -> { updateLanguage(new Locale("sk", "SK")); });
Selecting a Slovak radio button menu item, we call the updateLanguage()
method and pass a Slovak locale as a parameter.

In this tutorial, we have covered the Java ResourceBundle
. We created two console and one GUI applications. You might also want to look at the related tutorials: Java Swing tutorial , Java tutorial , or Displaying image in Java tutorial .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论