I am having problems with my Scanner. Click the button, and text from the second file should display. I got the button working, however the programme skips straight to the last line of the new textfile. Because of the slow load time, I think it’s because I can’t close my first scanner. I don’t think my layout is helping matters a lot, as there are going to be a lot of text files read one at a time, but writing the second class as an inner class makes things extra complicated it seems.
How do I make the scanner from the second class accessible to the first (and thus, use reader.close() )?
Should I be using nested/inner classes to boot the programme up?
Is there a cleaner method to start the programme and then prime the scanner for later actions?
Lastly, I’ve been trying to conform to SSCCE, am I any close? Thanks for your help
import declarations
public class MihatteFrame extends JFrame implements ActionListener{
....
public MihatteFrame() {
area
textfield
button
}
displayText method
checkTextFieldText method
public void actionPerformed(ActionEvent e) {
try {
if (textField.getText().equals("proceed to the entrance")) {
Scanner.close();
Scanner reader2 = new Scanner(new File("(Start) Front Gate.txt"));
while (reader2.hasNextLine()) {
String line = reader2.nextLine();
displayText(line);
try {
if(!line.trim().equals("")){
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
}
} else {
while (textField.getText() == null) {
displayText("I`m sorry, could you say that again?");
}
}
} catch (IOException ioe) {
}
}
x
import declarations
class ShowIntro {
public static void main(String args[]) throws IOException {
MihatteFrame mf = new MihatteFrame();
Scanner reader = new Scanner(new File("(Start) Introduction.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
mf.displayText(line);
try {
if(!line.trim().equals("")){
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
}
The GUI thread only performs actions when you return from an events it calls you with. This means if you do lots of actions, you will only see the cumulation of these action and if you pause for any reason, your GUI will pause.
You need to perform the action, in another thread so the GUI thread can update the screen. You also need to use SwingUtils.invokeLater() to update the GUI from a second thread.