very new to writing Java, so am grateful for any help I can get.
I`m trying to create JFrame with text in it read from a separate text file (there are 5 paragraphs, each appearing one after the other). I need help making the text appear on the JFrame (not so worried about the delayed effect for now), as so far, not been successful. Am I far off the mark with the code below? I know this a common problem, but other threads have been dealing with events and other (for me) difficult ideas, and taking what I need from such code is still a challenge for me.
I have read I need a JLabel for the text to go on (although elsewhere I read JPanel?). I believe I also need a method for displaying the text in the StoryFrame class, where I can add the JLabel (and possibly state the nextLine commands so as to help create the delayed effect, instead of putting it into my ShowIntro class – I intend to repeat this process repeatedly). The cmd also made me aware that I have a call to a non-static method from a static place – tried looking in my Java for Dummies text but still can`t figure out how to resolve this. I know this code is insufficient, what am I missing?
import javax.swing.JFrame;
import javax.swing.JLabel;
public class StoryFrame extends JFrame {
public StoryFrame() {
setTitle("見張ってしながら...");
setSize(400,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void displayText() {
JLabel Text = new JLabel();
add(Text); // I feel I need to add a lot more here to connect the two classes
}
}
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class ShowIntro {
public static void main(String args[])
throws IOException {
new StoryFrame();
Scanner reader = new Scanner(new File("Intro.txt"));
while (reader.hasNext()) {
StoryFrame.displayText();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
}
When looking at your
ShowIntroclass I notice 2 strange things:displayText()) on a class.To fix (1) you should pass the instance of the StoryFrame class into a variable, and replace
StoryFramewith the name of this variable in the marked line.To fix (2) you should add one parameter to the method
displayText(), so replace the header of that method in the StoryFrame class withpublic void displayText(String text) {and pass the text read by the scanner when you call the method from theShowIntroclass.Corrected version (untested)
And the
displayText()method from the StoryFrame class: