-1

I have a scanner that can read a txt file that I am trying to print on the screen. I am trying to do this by printing the scanner (scan) results of what the user typed in on the on the screen using Graphics g.

Any Ides on how to do this a different way Thank You :)

try {
    Scanner scan = new Scanner(new File("/Users/AlexSpallone/Desktop/name.txt"));
      msg = " Your Name is" + scan;
     } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2540802
  • 95
  • 1
  • 1
  • 4

3 Answers3

2

You should call the nextLine method on your Scanner object:

try {
Scanner scan = new Scanner(new File("/Users/AlexSpallone/Desktop/name.txt"));
  msg = " Your Name is" + scan.nextLine();
 } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
jh314
  • 27,144
  • 16
  • 62
  • 82
  • No i dont want it being wrote in the console I meant on a gui. How would I draw it using a string? – user2540802 Jul 19 '13 at 21:30
  • You would need to do what he is saying to get the string, but drawing it on the GUI is another matter. – tbodt Jul 19 '13 at 21:32
1

Take a look at How to use text areas

String msg = null;
try {
    Scanner scan = new Scanner(new File("/Users/AlexSpallone/Desktop/name.txt"));
    msg = " Your Name is" + scan.nextLine();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
JTextArea ta = new JTextArea(msg);
add(new JScrollPane(ta));

Equally, if it's just a small String, you could just use a JLabel. See How to use labels for more details

I'd also take a look at Creating a UI with Swing

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

Use this code:

public class MyPanel extends JPanel {
    public void paintComponenet(Graphics g) {
        super.paintComponent(g);
        try {
            Scanner scan = new Scanner(new File("/Users/AlexSpallone/Desktop/name.txt"));
            msg = " Your Name is" + scan.nextLine();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        g.drawString(20, 20, msg);
    }
}

Then add an object of this class to a JFrame.

tbodt
  • 16,609
  • 6
  • 58
  • 83
  • 1
    Why? Apart from the fact that if the file is a large file, it will block the EDT and make the program look like it's frozen, it won't handle things like long lines, word wrapping, scrolling etc... – MadProgrammer Jul 19 '13 at 21:52
  • I know. I was in a hurry to write an answer. – tbodt Jul 19 '13 at 21:53
  • Give the OP doesn't seem to have any concept of Swing, throwing into the fire with the oil seems a little harsh - IMHO ;) – MadProgrammer Jul 19 '13 at 21:56
  • Then why didn't you fix your answer? Why haven't you yet fixed your answer yet? This is very bad advice that should either be repaired or deleted. – Hovercraft Full Of Eels Jul 28 '13 at 21:53