问题描述
我需要在应用程序的所有文本区域中将默认语言更改为希伯来语。我尝试使用Set Local,但是没有用。
有什么主意吗?
解决方法
下面的代码演示了我所知配置JTextComponent
(JTextArea
是其子类)的唯一方法,以便在获得输入焦点时显示希伯来语字符。换句话说,在JTextComponent
获得关注之后和用户开始输入文本之前,用户无需显式更改语言。
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.im.InputContext;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class DfltHbrw implements ActionListener,FocusListener,Runnable {
private static final Locale HEBREW = new Locale("iw","IL");
private static final String EXIT = "\u05E1\u05D2\u05D5\u05E8";
private JFrame frame;
private JTextArea textArea;
@Override // java.awt.event.ActionEvent
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
if (EXIT.equals(actionCommand)) {
System.exit(0);
}
}
@Override // java.awt.event.FocusListener
public void focusGained(FocusEvent event) {
InputContext ic = textArea.getInputContext();
ic.selectInputMethod(HEBREW);
}
@Override // java.awt.event.FocusListener
public void focusLost(FocusEvent event) {
// Do nothing.
}
@Override // java.lang.Runnable
public void run() {
showGui();
}
private JPanel createButtons() {
JPanel buttonsPanel = new JPanel();
JButton button = new JButton(EXIT);
button.addActionListener(this);
buttonsPanel.add(button);
return buttonsPanel;
}
private JScrollPane createTextArea() {
textArea = new JTextArea(20,60);
textArea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
textArea.addFocusListener(this);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
return scrollPane;
}
private void showGui() {
frame = new JFrame("Hebrew");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createTextArea(),BorderLayout.CENTER);
frame.add(createButtons(),BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new DfltHbrw());
}
}
我只添加了JButton
,以便有多个[GUI]组件,以便将焦点从一个组件转移到另一个组件。
上面代码的相关部分是focusGained()
方法。我在JTextArea
上添加了 focus监听器,当JTextArea
获得焦点时,该调用该方法。实际上,focusGained()
方法实际上是配置JTextArea
以便在用户开始向其中输入文本时显示希伯来语的工作。
请注意,可以使用相同的focusGained()
方法将JTextArea
配置为显示任何[受支持的]语言。您只需更改传递到Locale
方法的selectInputMethod()
参数即可。
还要注意,我只设置了ComponentOrientation
,以使JTextArea
中的希伯来语文本看起来“自然”。不需要配置JTextArea
来显示希伯来语。