Taking input from console in a plugin in java

久未见 提交于 2019-12-24 09:39:55

问题


I am developing an Eclipse plugin and I want to take input from the user. I had a problem before with dealing with the console as I have 2 consoles 1 in the original Eclipse application and the other in the new opened Eclipse plugin window. I used the method shown below to print in the Console of the Plugin

public static void writeToConsole(String output) {

        MessageConsole console = new MessageConsole("My Console", null);
        console.activate();
        ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console });
        MessageConsoleStream stream = console.newMessageStream();
        stream.println(output);
    }

I just don't know how to write in the console and take what's written in a variable

N.B. The normal methods like

BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();


    System.out.println(s);

are working for the original Eclipse not the plugin


回答1:


You can't tie up the UI waiting for user input so you have to handle user input when it is received. One way to do this is with a document listener. Here is an example that prints the last line typed:

        console.getDocument().addDocumentListener(new IDocumentListener() {
            @Override
            public void documentChanged(final DocumentEvent event) {
                if ("\r\n".equals(event.getText())) {
                    final IDocument doc = event.getDocument();
                    try {
                        final IRegion region = doc.getLineInformationOfOffset(event.getOffset());
                        try {
                            final String line = doc.get(region.getOffset(), region.getLength());
                            System.out.println(line);
                        } catch (BadLocationException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } catch (BadLocationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void documentAboutToBeChanged(final DocumentEvent event) {
                // TODO Auto-generated method stub                    
            }
        });


来源:https://stackoverflow.com/questions/17045811/taking-input-from-console-in-a-plugin-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!