Reputation: 18068
I wanted to make a demo of reading input from console then using JOptionPane
. If I first type br.readLine()
then use JOption...
the input dialog is not showing and I can still write in the console like somebody would wait for it... I want input dialog to show up.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class Kalkulator {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type number");
int liczba1 = Integer.valueOf(br.readLine());
br.close();
int liczba2 = Integer.valueOf(JOptionPane.showInputDialog("Type number"));
System.out.println(liczba1 + liczba2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 45
Reputation: 1075537
You can always type in the console. No one has to be listening. When you type in the console, the characters are stored in a buffer called a stream. If no one is reading the stream, the character just queue up. Calling br.readLine()
draws characters out of the stream until a newline is seen.
Most consoles these days echo the characters typed themselves, and you can't generally turn that off, so even when you've stopped listening, the user can still type (pointlessly). If you don't want them to, and you think they probably will, the best you can do is output a message telling them not to (politely).
Upvotes: 2
Reputation: 477676
Simply because System.in
is a stream. When you type, you provide data. That data is stored in some kind of queue.
When one calls br.readLine
, a part of the queue is read out (and sometimes blocks until data is provided)...
Closing a stream simply means that you recycle some resources (like for instance mark a file again as available). Now a console keeps accepting data. You only won't read it anymore.
It is up to the console program (bash
, sh
, cmd.exe
,...) to handle the fact that a user enters data. A console program then redirects the entered values to System.in
. Java has no control over that program...
Upvotes: 4