gpt4 book ai didi

java - 如何调用接受字符串的方法?

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:02 24 4
gpt4 key购买 nike

我正在尝试保存用户使用 JFileChooser 选择的 .txt 文件。

我有3种方法

事物 1 获取文件路径并将其存储到名为 File1 的字符串中。

事物 2 需要此字符串才能将文件保存在正确的位置。

但是,当我在 GUI ActionPerformed 中运行 thing2 时,它会给我一个错误,因为它需要传入一个字符串。我传入“String File1”,但它不起作用。

事情1

JFileChooser chooser;
String choosertitle = null;
String File1 = null;

chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

chooser.setAcceptAllFileFilterUsed(true);

if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File1 = chooser.getCurrentDirectory() + "";
}
else {
JOptionPane.showMessageDialog(null,"No Selection ");

}

fileTextField.setText(File1);
return File1;

事情2

      String nameOfFile = (""); 
String choice = comboBox.getSelectedItem() + "";

JOptionPane.showMessageDialog(null,File1);


if ("All Messages".equals(choice)){
nameOfFile = ("Messages");
} else if
("All Email Address".equals(choice)){
nameOfFile = ("Address Book");
}

File f = new File (File1 + nameOfFile+ ".txt");
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("This is a file created by Joe ");
fw.close();
} catch (IOException ex) {
Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
}


boolean allFieldsCheck = !choice.equals("Please Select What You Would Like To Export") && !fileTextField.equals("");
if (allFieldsCheck == false) {
InputError ipe = new InputError();
ipe.setVisible(true);
} else {
//add new message
}

已执行的操作

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

thing2(String File1);

}

我想要上面的代码做的就是获取用户想要保存文件的位置,然后将其保存在那里。

任何帮助将不胜感激,因为我是新手

最佳答案

您必须修改 exportButtonActionPerformed() 方法:

private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
thing2(File1);
}

但是 thing1 中定义的变量 File1 必须从此方法中可见,例如:

public class AClass
{
/* declared here in order to be visible both from thing1 and to ActionPerformed */
private String File1 = null;

/* thing1 */
public void AMethod() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

chooser.setAcceptAllFileFilterUsed(true);

if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File1 = chooser.getCurrentDirectory() + "";
fileTextField.setText(File1);
} else
JOptionPane.showMessageDialog(null,"No Selection ");
}

/* ... */

/* ActionPerformed */
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {
thing2(File1);
}
}

关于java - 如何调用接受字符串的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com