有了这个程序,我试图让用户选择一个表示4x4数独问题的文本文件。然后我的代理人将采取此文件并尝试解决数独谜题。程序不会等待模态对话框
我遇到的问题是,我似乎无法弄清楚如何获得正确的文件选择,然后传递到方法调用进行处理。
这是我创建的文件选择器类。到目前为止,它成功地启动了一个按钮,点击后可以调出计算机的文件结构,以便用户选择文件。
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* Created by neil on 7/12/17.
*/
public class file_selector {
public JPanel panel1;
public File file;
JButton button1;
public file_selector() {
final JFileChooser fc = new JFileChooser();
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
System.out.println("You chose to open " + file.getName());
}
}
});
}
public File getFile() {
return file;
}
}
这是我尝试使用用户选择的文件的主要方法。当我把函数调用放在一个while循环中时(就像它现在一样),它永远不会继续,因为文件从未设置。如果我不在while循环中放入函数调用,当我尝试处理文件时,由于文件的值为空,我得到一个nullPointerException错误。
public class sudoku {
//create 2d array that represents the 16x16 world
public cell[][] world_array = new cell[15][15];
static File myFile;
ArrayList<String> world_constraints;
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("file_selector");
file_selector fs = new file_selector();
frame.setContentPane(fs.panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
myFile = fs.getFile();
while(myFile != null) {
sudoku my_puzzle = new sudoku();
my_puzzle.solve_puzzle();
}
}
我做了一吨的搜索,似乎无法找到什么毛病我file_selector类,使得它不设置该文件的用户选择的值。
感谢您的输入!我实际上继续前进,刚刚删除了我创建的按钮,并在程序启动时立即弹出JFileChooser对话框。在此配置下,程序在继续之前等待用户选择输入文件。 –