[英]How to change text in JFileChooser?
在JFileChooser Java swing 組件中,我需要更改所有文本元素(用於翻譯):
文件名: (JLabel)
文件類型: (JLabel)
取消(J按鈕)
不幸的是,這不是任何方法。
有什么辦法可以做到嗎?
謝謝!
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();
showDialog()
用於顯示自定義對話框(例如,不是打開或保存對話框)。 它有一個參數來指定批准按鈕的文本。 如果尚未使用setDialogTitle()
方法設置標題,則實現會任意選擇使用批准按鈕的文本作為 Windows 操作系統上的標題,但是這在任何地方都沒有記錄,您不應指望這會起作用。
如果您想要自定義標題,請使用setDialogTitle()
。 如果您想要自定義批准按鈕文本,請使用setApproveButtonText()
。 顯然showDialog()
也接受批准按鈕的文本,在這種情況下,您不需要事先調用setApproveButtonText()
。
如果需要打開對話框,請使用showOpenDialog()
方法。 如果您想要保存對話框,請使用showSaveDialog()
。 如果您想要自定義對話框,請僅使用showDialog()
。
如果您只需要翻譯JFileChooser
文本,我建議您更改JFileChooser
區域設置(通過調用JFileChooser#setLocale(Locale)
)而不是侵入JFileChooser
的內部。 實際上,所有JFileChooser
文本都依賴於語言環境。 因此,將語言環境更改為您想要的語言環境將更輕松地更改這些文本。
通常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()
protected void installStrings(JFileChooser paramJFileChooser)
的調用不使用語言環境,而其他 installStrings() 方法(例如在 BasicFileChooserUI 中)使用protected void installStrings(JFileChooser)
的語言環境protected void installStrings(JFileChooser)
方法。
Aqua: 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!");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.