开发者

How do I get input from System.in (Java) in Netbeans?

开发者 https://www.devze.com 2022-12-10 17:37 出处:网络
I have a small Java test app in Netbeans where the main() cl开发者_StackOverflowass reads input from System.in. How can I open a window into which I can type input? (I am using NB 6.7.1 on Windows 7).

I have a small Java test app in Netbeans where the main() cl开发者_StackOverflowass reads input from System.in. How can I open a window into which I can type input? (I am using NB 6.7.1 on Windows 7).


It may not be obvious but in Netbeans the Output tab at the bottom also takes input if your main thread is waiting for input. Just type under the last output line and hit enter. In other words, the Output tab is the same as a console window.


I'm pretty confident the following worked in NB 6.5 Just type into the output window which happens to accept input

InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(inputStreamReader);
System.out.println("Type name:");
String name = reader.readLine();
System.out.println("Hello "+name);


In Eclipse, you can just type in your console window. I suppose Netbeans would have a similar option.


If you just want a small window to type some input into, then the easiest way is to use JOptionPane. For example:

import javax.swing.JOptionPane;

public class TestClass {
    public static void main(String[] args) {
        String answer;
        answer = JOptionPane.showInputDialog(null, "What number to multiply by 3?");
        int num = Integer.parseInt(answer);
        num = num * 3;
        JOptionPane.showMessageDialog(null, "The answer is " + num);
    }
}

Note that showInputDialog returns a String, so you'll have to convert the data to whatever format you need. If you have something more involved, then JOptionPane may not be the way to go.


if you are asking for a visual input, NetBeans provides a very easy way to manage visual components, as easy as drag-and-drop

how to do it:

  • Create a JFrame by right-click on your package > New > JFrame form
  • you can see a "source" tab and a "design" tab on top of the frame.
  • drag and drop your visual components (like Text Field from the Swing Control on the right menu)
  • after placing your component(s) on the Frame, right-click > Events > (then choose the type of event you want to handle for each component)

it may look difficult and scary for first-timers, but once you start playing with it, few minutes and you will enjoy your experiments ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消