问题
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