Reputation: 1
I am proficient in Java but I have never made a GUI before & am trying to learn them. I'm trying to program a basic GUI for a 20 questions game I wrote a while ago. The user has the option to upload memory for the game in the form of a .txt file, and I'm having a lot of difficulty finding info on the JFileChooser/getting it to work. I can't get any of the buttons to work, do I need to create actionPerfomeds for the fileChooser too? Also, how do I restrict it to ONLY .txt files? (game is the name of the 20 questions object I wrote earlier).
JFileChooser fileChooser = new JFileChooser();
fileChooser.setPreferredSize(new Dimension(410, 250));
panel3.add(fileName, BorderLayout.NORTH);
panel3.add(fileChooser, BorderLayout.SOUTH);
frame.pack();
frame.validate();
frame.repaint();
Scanner scan = new Scanner(fileChooser.getName());
game.load(scan);
Upvotes: 0
Views: 49
Reputation: 687
Your code doesn't wait for a user response. So, yeah, you need an actionPerformed
method to check the output of the file chooser. See https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html for how to use the file chooser. You need to capture the return value of a #showOpenDialog
call and then call #getSelectedFile
.
Scroll down on that same page for how to use a FileFilter
to just get .txt files.
Upvotes: 1