gpt4 book ai didi

java - 单击按钮后如何使用 jFileChooser 读取文件?

转载 作者:行者123 更新时间:2023-11-30 11:20:47 24 4
gpt4 key购买 nike

我想使用 jFileChooser 读取一个文件。按下按钮(例如 jbutton1ChooseFile)并选择所需文件后,jFileChooser 将出现。选择完成后,将使用另一个按钮(比如 jbutton2)读取用户刚刚选择的文件的内容。因此,在单击 jbutton2 时,将读取选定的文件。

我发布了几行代码,以便于理解我的意思:

     private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {                                                             
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:

JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);

jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;

case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;

case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}

到目前为止,它运行良好。现在,jButton2 的代码如下:

        private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {                                                       
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();

try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}

任何帮助将不胜感激。

最佳答案

乍一看,问题似乎是您正在为 JFileChooser 使用局部变量。也就是说,你有一行:

JFileChooser loadFile= new JFileChooser();

在您的 jButton1ChooseFileChooseFileActionPerformed 函数中,还尝试在您的 jButton2EncryptEncryptActionPerformed 函数中引用 loadFile

为了使 loadFile 对象对两者都可用,您需要让 loadFile 对象成为两个函数所属类的成员。

关于java - 单击按钮后如何使用 jFileChooser 读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22565829/

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