1

After thinking I was on course to solving a problem with making text (read from a file) appear in a JPanel, I`m frustratingly back to square one.

The code is below. The result is just a blank screen 400x500 screen. Some combinations of using nextLine() + nextLine() as displayText commands result in one word coming up from the file (the word has been different multiple times). This makes me wonder: do I need code that deals with text wrapping? The textfile itself is in paragraphs, and as such, I thought that sf.displayText should say sf.displayText(reader.next() + reader.nextline() + reader.nextline(), and have tried other combinations, but this may be confusing the while parameters. Have also tried a different textfile with simple sentences, no paragraphs, but again, nothing comes up.

Having looked online, I have found that layouts may be an issue, and that alternative options may be BufferedReader or using JTextArea. Browsing through Big Java didn`t provide anything I felt I could take, as all discussion on the scanner went towards integers, whereas the file I want read is prose. I also tried putting a small piece of text in the code itself and cancelling out everything else below it to see if I could transfer text from the code to the JPanel:

StoryFrame sf = new StoryFrame();
sf.displayText("Life is beautiful"); 

but still nothing came up. Ultimately, I want to put text from a file into a JPanel, and have each paragraph come up 5 seconds after the one before. So ultimately, my questions are:

  • Why does my text fail to show up, or only display one word? Is it because I don`t specify a layout?
  • Do I need to think about text wrapping?
  • Should I look into JTextArea instead of JPanel, and BufferedReader instead of Scanner?
  • Have I been using the nextLine method from the Scanner correctly?
  • Can I put a command to read a file and display that file`s text in the display method of StoryFrame (I think this would make things a lot easier)?

I know it`s a lot, so any answers to any of the questions would be greatly appreciated, thank you. Tom

import javax.swing.JFrame;
import javax.swing.JLabel;

public class StoryFrame extends JFrame {

private JLabel mylabel;
public StoryFrame() {

    setTitle("見張ってしながら...");
    setSize(400,500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    mylabel = new JLabel();
    this.add(mylabel);
    setVisible(true);
}


public void displayText(String text) {
    JLabel storyText = new JLabel();
    add(storyText);
}

}

ShowIntro

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

class ShowIntro {
 public static void main(String args[]) 
        throws IOException {

StoryFrame sf = new StoryFrame();
Scanner reader = new Scanner(new File("Try.txt"));

while (reader.hasNextLine()) {
    //String line = in.nextLine() Not sure whether this would contribute, I doubt it does though
    sf.displayText(reader.next()); 
            //sf.displayText(reader.next() + reader.nextLine() + reader.nextLine()); was also attempted.

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {          }
}

 }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Tom Pengelly
  • 67
  • 2
  • 2
  • 9

2 Answers2

3

it fails because you never call a method to use the text in your displaytext method

public void displayText(String text) {
    mylabel.setText(text);
}
schippi
  • 1,034
  • 5
  • 15
  • Thank you for that. Added the changes as per your comment and comment below. Progress as it is, the only thing that is displayed is the last line however. I tried to add another "reader.nextLine" command but get back a NoSuchElementException (which confirms its reading only the last line). How do I get it to read from the top of the file to the bottom, and as such display all of the text? – Tom Pengelly Dec 02 '12 at 14:37
2

You are also reading the file one word at a time:

  sf.displayText(reader.next()); 

should be:

   sf.displayText(reader.nextLine());

if you want to read upto the next newline character.


Even though this was not in the original question to satisfy some of the comments below here is a modified version of the program

package com.vincentramdhanie.kitchensink;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;

public class StoryFrame extends JFrame {

    private JTextArea area;
    public StoryFrame() {

        setTitle("見張ってしながら...");
        setSize(400,500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        area = new JTextArea(10, 30);
        area.setEditable(false); 
        area.setCursor(null); 
        area.setOpaque(false); 
        area.setFocusable(false);
        this.add(area);
        setVisible(true);
    }


    public void displayText(String text) {
        area.setText(text);
    }

    public static void main(String args[]) 
        throws IOException {

        StoryFrame sf = new StoryFrame();
        Scanner reader = new Scanner(new File("Try.txt"));

        while (reader.hasNextLine()) {                
             String line = reader.nextLine();
             sf.displayText(line); 
             try {
                //to skip blank lines. If the line has no non-space characters then do not sleep
               if(!line.trim().equals("")){
                  Thread.sleep(5000);
               }
             } catch (InterruptedException e) {          }
        }
     }
}
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • Thank you for clearing that up for me - That confused me for a while! If I may ask another question though, "reader.nextLine" reads only one line - I thought in a while loop, it would repeat with the line below, is this right? And does it do the same if the line below is a space (to separate paragraphs for example)? – Tom Pengelly Dec 02 '12 at 14:51
  • 1
    Every call to nextLine() will read upto the next line separator. Then position the cursor at the first character of the next line. You can experiment with a blank line in the file and see what happens. In your loop you can trim() the String that you get and check if it is empty and not display it if that is the case. – Vincent Ramdhanie Dec 02 '12 at 15:39
  • Ok, had a little play - two problems - (1)only the last of the 6 paragraphs will be displayed on the panel (as is the case with other test files, the last line only gets displayed) in the centre, and (2) if the line is too long, the panel just displays "..." at the end and cuts off the rest of the paragraph (ie. no wordwrap). Any idea as to what I`m doing/not doing? If my understanding is right, trimming is not the issue. :-\ – Tom Pengelly Dec 03 '12 at 09:22
  • 1
    If the text is very long you can use a JTextArea instead and set some properties to make it behave like a label. `textArea.setEditable(false); textArea.setCursor(null); textArea.setOpaque(false); textArea.setFocusable(false); ` – Vincent Ramdhanie Dec 03 '12 at 10:37
  • Shall experiment tomorrow and get back to you, thank you kindly for the tip :-) – Tom Pengelly Dec 03 '12 at 14:55
  • Ok, created a JTextArea. Am getting back a nullpointerexception, not sure what I`ve failed to designate as the text read from file, especially as with Jlabel, it didn`t seem to present any problems re. scanner. I know if clause is useles sbecause "what is text?", how do I say in advance that there will be a file with text? (sorry, struggling to add code with comments) --`private JTextArea area` --`... //code constructing the frame` --`public void displayText(String text) {` --`if(text != null) {` --`area.setText(text)` --`}` --`}` – Tom Pengelly Dec 05 '12 at 05:11
  • Did you instantiate the textarea? `area = new JTextArea()` in the constructor of the JFrame? – Vincent Ramdhanie Dec 05 '12 at 10:39
  • Ok, I changed it (I had originally used `JTextArea area = new JTextArea()` thinking that`s how you instantiate something), thank you for that. So everything`s compiled but am still getting a blank JFrame with no text. My method now reads `public void displayText(String text) { area.setText(text); }` and the method that calls the frame reads `while (reader.hasNextLine()) { mf.displayText(reader.nextLine()); }` (mf being the call to create the JFrame object). Does the Scanner method need to be in the JFrame method? – Tom Pengelly Dec 05 '12 at 13:46
  • 1
    I added a modified version of thye code to the answer so you can see what the whole thing may look like. You can then look at the API docs for JTextArea to further modify the behaviour and look. – Vincent Ramdhanie Dec 05 '12 at 14:44
  • Thank you kindly for your time and patience, you`ve helped me gain some knowledge I didn`t have when asking this question. Very much appreciated. – Tom Pengelly Dec 06 '12 at 13:08