tags:

views:

260

answers:

3
+3  Q: 

Java: Scanner

Scanner can only get input from system console? not be able to get from any dialog window?

Thanks.

+7  A: 

A Scanner can read text from any object which implements the Readable interface.

That includes BufferedReader, CharArrayReader, CharBuffer, FileReader, FilterReader, InputStreamReader, LineNumberReader, PipedReader, PushbackReader, and StringReader (from the Readable javadoc). Unfortunately, that does not include any dialog windows.

The easiest way to hook a dialog window to a Scanner would probably be to build a Scanner using the constructor that takes a String, passing the user input from the dialog directly to the Scanner.

Bill the Lizard
It would certainly be possible to configure a dialog window to flow data throw an InputStream, which could then be hooked to a Scanner.
Greg Case
Certainly possible. There are so many more straightforward ways to get user input from a dialog, that I've never considered this possibility before.
Bill the Lizard
Certainly true. I think the root of the original question may simply be a lack of knowledge or understanding about the alternatives. I have certainly observed - recently, even - Scanner being used as the first option for input in a situation where it was clearly not the appropriate choice.
Greg Case
Also, side comment - why make a StringReader? Scanners can already be created directly on Strings; the additional layer would only add overhead.
Greg Case
@Greg: Right again. I've never used that constructor before. :) I think the reason for the question might be so that they can use some of Scanner's convenience methods for parsing input.
Bill the Lizard
+1  A: 

No; a Scanner may be created for any number of possible inputs: Files, InputStreams, ReadableByteChannels, Strings, and anything that supports the Readable interface. See the Constructor Summary.

Greg Case
A: 

Well, I tried with the example given at Best way to determine the total number of words of a file in Java?: just replace new File("my-text-file.txt") with a String variable, and it works...

So if you get the textual content of the component into a String, you can use Scanner.

PhiLho