gpt4 book ai didi

java - 值未存储在变量中

转载 作者:行者123 更新时间:2023-12-02 06:10:52 26 4
gpt4 key购买 nike

这是一个使用 JFileChooser 的程序:

package execute;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class FCDemo extends JFrame
{
JFileChooser fc = new JFileChooser();
private String fileName;

public FCDemo(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel pnl = new JPanel();
pnl.setLayout(new GridLayout(2, 1));

JButton btn = new JButton("JFileChooser.showOpenDialog() Demo");
ActionListener al;
al = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
switch (fc.showOpenDialog(FCDemo.this))
{
case JFileChooser.APPROVE_OPTION:
fileName=fc.getSelectedFile().getName();
JOptionPane.showMessageDialog(FCDemo.this, "Selected: "+fc.getSelectedFile(),"FCDemo",JOptionPane.OK_OPTION);
break;

case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(FCDemo.this, "Cancelled","FCDemo",JOptionPane.OK_OPTION);
break;

case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(FCDemo.this, "Error","FCDemo",JOptionPane.OK_OPTION);
}

}
};
btn.addActionListener(al);
pnl.add(btn);

setContentPane(pnl);

pack();
setVisible(true);
}

public String get_fileName(){
return fileName;
}


public static void main(String[] args)
{

FCDemo demo=new FCDemo("filechooser");
System.out.println("the file name is= "+demo.get_fileName());
}
}

由于某种原因,所选文件的目录未存储在名为 fileName 的字符串变量中。当我将 fileName 打印到控制台时,我得到 null谁能帮我解决这个问题吗?

最佳答案

您的主线程在所选文件之前执行。这就是文件名被打印为空的原因。要查看您选择的文件,请尝试使主线程 hibernate 10 秒钟。并选择您的文件。之后您可以在 main.c 中看到选定的文件。使用:

public static void main(String[] args)
{
FCDemo demo=new FCDemo("filechooser");
try {
Thread.sleep(10000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("the file name is= "+demo.get_fileName());
}

关于java - 值未存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21900018/

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