在JFileChooser Java swing 组件中,我需要更改所有文本元素(用于翻译):
文件名:(JLabel)
文件类型:(JLabel)
取消(JButton)
不幸的是,这不是任何方法..
有什么办法可以做到吗?
谢谢!
在JFileChooser Java swing 组件中,我需要更改所有文本元素(用于翻译):
文件名:(JLabel)
文件类型:(JLabel)
取消(JButton)
不幸的是,这不是任何方法..
有什么办法可以做到吗?
谢谢!
Java 中的 Swing 组件完全能够理解国际化。本文解释了细节并展示了如何实现它的示例。
UIManager.put("FileChooser.fileNameLabelText", "FileName");
UIManager.put("FileChooser.filesOfTypeLabelText", "TypeFiles");
使用 UIManager
UIManager.put("FileChooser.saveButtonText","Custom text acept");
UIManager.put("FileChooser.cancelButtonText","custom text to cancel");
JFileChooser fileChooser = new JFileChooser();
如果您只需要翻译JFileChooser
文本,我建议您更改JFileChooser
语言环境(通过调用JFileChooser#setLocale(Locale)
)而不是侵入JFileChooser
其内部。事实上,所有JFileChooser
文本都依赖于语言环境。因此,将语言环境更改为您想要的语言环境会更轻松地更改这些文本。
showDialog()
用于显示自定义对话框(例如,不是打开或保存对话框)。它有一个参数来指定批准按钮的文本。如果标题尚未使用该setDialogTitle()
方法设置,则实现任意选择使用批准按钮的文本作为 Windows 操作系统上的标题,但是这在任何地方都没有记录,您不应该指望它起作用。
如果您想要自定义标题,请使用setDialogTitle()
. 如果您想要自定义批准按钮文本,请使用setApproveButtonText()
. 显然showDialog()
也需要批准按钮的文本,在这种情况下你不需要setApproveButtonText()
事先打电话。
如果您想要打开对话框,请使用该showOpenDialog()
方法。如果您想要保存对话框,请使用showSaveDialog()
. 仅showDialog()
在需要自定义对话框时使用。
通常JFileChooser@setLocale(Locale)
像 Riduidel 所说的那样工作。在 Mac OSX 上,虽然这被忽略了。
在 Mac OSX 上正确设置您调用的默认语言环境请UIManager.getLookAndFeelDefaults().setDefaultLocale(Locale);
注意,这仅适用于 Java 8,不适用于 Java 7!
似乎即使对于您UIManager.getDefaults().setDefaultLocale(Locale);
用于 Aqua 外观的所有其他外观和感觉,这也不起作用。看起来在AquaFileChooserUI.java
方法protected void installStrings(JFileChooser paramJFileChooser)
中调用UIManager.getString()
不使用语言环境,而其他 installStrings() 方法,例如在 BasicFileChooserUI 中,确实使用protected void installStrings(JFileChooser)
方法中的语言环境。
水族: UIManager.getString("FileChooser.cancelButtonText");
基本的:UIManager.getString("FileChooser.cancelButtonText",l);
fileChooser.setLocale(Locale);
虽然在 OSX 上仍然被忽略。
此答案是 Fasimba/Icewalker 在DevX Java 论坛上发布的答案的修改版本。1我已经引用了他的回答,只是修改了搜索和替换参数。我不相信其中表达的逻辑。
public void changeButtonText (Component c, String original, String change) {
if (c instanceof JButton) {
JButton b = (JButton) c;
if (b.getText() != null && b.getText().equalsIgnoreCase(original))
b.setText(change);
} else if (c instanceof Container) {
Container cont = (Container) c;
for (int i = 0; i < cont.getComponents().length; i++) {
changeButtonText (cont.getComponent(i), original, change);
}
}
}
如下调用它:
// dirChooser is the JFileChooser instance
for (Component c : dirChooser.getComponents()) changeButtonText(c, "Cancel", "Don't do it!");