如何重命名文件选择器中的按钮,例如从“打开”重命名为“另存为”
saveAsButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
try(FileWriter fw = new FileWriter(chooser.getSelectedFile()+".txt")) {
fw.write(textPane1.getText().toString());
fw.flush();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
最佳答案
使用JFileChooser#showSaveDialog
而不是JFileChooser#showOpenDialog
我建议看看How to Use File Choosers和 JavaDocs了解更多详情
当然,如果您想对按钮文本进行更多控制,那么您应该看看 JFileChooser#setApproveButtonText
及其相关方法
approveButtonText is reset to defaul, if showOpenDialog or showSaveDialog is called
你知道,这很有趣,我已经使用这种方法很多年了,而且它似乎一直有效。
我深入研究了 JFileChooser
代码,发现 showOpen/SaveDialog
调用了这个...
public void setDialogType(int dialogType) {
if(this.dialogType == dialogType) {
return;
}
checkDialogType(dialogType);
int oldValue = this.dialogType;
this.dialogType = dialogType;
if(dialogType == OPEN_DIALOG || dialogType == SAVE_DIALOG) {
setApproveButtonText(null);
}
firePropertyChange(DIALOG_TYPE_CHANGED_PROPERTY, oldValue, dialogType);
}
这个“应该”重置批准按钮文本,但由于某种原因,在我的测试中,showOpenDialog
有效,让我们谈谈奇怪的...
public class CustomFileChooser extends JFileChooser {
@Override
public void setDialogType(int dialogType) {
String currentApproveText = getApproveButtonText();
super.setDialogType(dialogType);
setApproveButtonText(currentApproveText);
}
}
那么,解决办法是什么?好吧,您可以使用 showDialog
来代替,它将其设置为 CUSTOM_DIALOG
,但我很懒:P
另一种解决方案可能是简单地覆盖setDialogType
并重新应用approveButtonText
,例如...
public class CustomFileChooser extends JFileChooser {
@Override
public void setDialogType(int dialogType) {
String currentApproveText = getApproveButtonText();
super.setDialogType(dialogType);
setApproveButtonText(currentApproveText);
}
}
关于java - 文件选择器上的重命名按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753695/