gpt4 book ai didi

Java 文件选择器循环

转载 作者:行者123 更新时间:2023-12-01 07:56:27 25 4
gpt4 key购买 nike

我正在开发一个程序,该程序打开JFileChooser并允​​许用户选择一个包含姓名、高度和体重等信息的.txt 文件。

然后,程序计算文件中列出的每个人的 BMI 并将其显示在 JOptionPane 中。然后他们可以决定是否选择另一个文件或取消该程序。

我已经弄清楚了计算和显示它们的所有内容,但我遇到的困难是 JOptionPane 选择。我想每当用户选择“否”选项或取消选择文件时显示一条消息,但我似乎无法这样做。我也不确定每当他们选择"is"选项时如何重新打开 JFileChooser 。如果有人可以提供一些关于如何实现这一目标甚至我可能做错了什么的指导,我将非常感谢您的帮助。先感谢您!到目前为止,这是我的代码:

public static void main(String[] args) throws FileNotFoundException, IOException {
readFile();
}

public static int readFile() throws FileNotFoundException, IOException {
int choice = (JOptionPane.YES_OPTION);

while (choice == (JOptionPane.YES_OPTION)) {
File file;
JFileChooser fileChooser;

fileChooser = new JFileChooser();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 300);
int returnVal = fileChooser.showOpenDialog(null);
while (returnVal == JFileChooser.APPROVE_OPTION) {

file = fileChooser.getSelectedFile();

String report = BMIRecord.report(file);

int dialogResult = JOptionPane.showConfirmDialog(null, report + "\n\nWould you like to try another file?", "BMI Calculations", JOptionPane.YES_NO_OPTION);
return choice;
}

}

while (choice == (JOptionPane.NO_OPTION)) {
JOptionPane.showMessageDialog(null, "Session ended.");
return choice;
}
return 0;
}

最佳答案

所有循环都使问题变得困惑。您只需要一个循环,即提示用户输入新文件并提示用户继续的方式...

基本上,您需要提示输入文件,如果JFileChooser返回JFileChooser.APPROVE_OPTION,您可以计算BMI并显示报告,然后可以提示用户另一个文件。否则,您可能会认为他们选择不继续。

继续执行此操作,直到 JOptionPane.showConfirmDialog 等于 JOptionPane.NO_OPTION(或者用户取消 JFileChooser,这可能是同样的事情)

类似...

public static int readFile() throws FileNotFoundException, IOException {

JFileChooser fileChooser = new JFileChooser();
int choice = JOptionPane.NO_OPTION;
do {
choice = JOptionPane.NO_OPTION;
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
String report = BMIRecord.report(file);
choice = JOptionPane.showConfirmDialog(null, report + "\n\nWould you like to try another file?", "BMI Calculations", JOptionPane.YES_NO_OPTION);
}

} while (choice == JOptionPane.YES_OPTION);

return 0;
}

例如...(ps,我不确定该方法“假设”返回什么,所以我只是返回0)

关于Java 文件选择器循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29441654/

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