Thursday, March 8, 2018

How to change language at runtime in java swing

I try to change the Locale at runtime in my swing application.
But I can't figure out how it supposed to work, or there are no master plan?



I can only think of two choices:
1. Restart the application, not the best user experience.
2. Create a localization manager that can register/unregister components, on a change it just iterate all components and change the text.



Both 1 and 2 feels awkward.



Other info:
For the moment the orientation is not a target.
The application is obfuscated.




Example:



LocRes_en.properties:





text1 = English text




LocRes_ja.properties





text1 = Japanese text



ChangeLocale.java:






import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class ChangeLocale {

private JFrame frame;

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {

try {
ChangeLocale window = new ChangeLocale();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}


public ChangeLocale() {
initialize();
}

private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 5, 5);
frame.getContentPane().setLayout(flowLayout);


JButton btnChangeLoc = new JButton("Change Locale");
frame.getContentPane().add(btnChangeLoc);

final JLabel lblLabel1 = new JLabel("New label");
frame.getContentPane().add(lblLabel1);
Locale.setDefault(new Locale("en"));
ResourceBundle r = ResourceBundle.getBundle("LocRes");
lblLabel1.setText(r.getString("text1"));


btnChangeLoc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Locale.setDefault(new Locale("ja"));
ResourceBundle r = ResourceBundle.getBundle("LocRes");
// Manually iterate through all components :(
lblLabel1.setText(r.getString("text1"));
//
}
});
}

}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...