Java Lanterna-如何从文本框中获取输入?
我是一个相对较新的Java程序员(大约有两个月的经验),我不知道如何将输入到(用于创建终端用户界面的库)文本框中的数据转换成字符串供以后使用 这是我的密码:Java Lanterna-如何从文本框中获取输入?,java,string,user-interface,textbox,lanterna,Java,String,User Interface,Textbox,Lanterna,我是一个相对较新的Java程序员(大约有两个月的经验),我不知道如何将输入到(用于创建终端用户界面的库)文本框中的数据转换成字符串供以后使用 这是我的密码: //Variables (that I can't seem to populate) final String usernameIn = null; final String passwordIn = null; //Username panel, contains Label and TextBox Panel username =
//Variables (that I can't seem to populate)
final String usernameIn = null;
final String passwordIn = null;
//Username panel, contains Label and TextBox
Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
username.addComponent(new Label("Username: "));
username.addComponent(new TextBox(null, 15));
addComponent(username);
//Password panel, contains label and PasswordBox
Panel password = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
password.addComponent(new Label("Password: "));
password.addComponent(new PasswordBox(null, 15));
addComponent(password);
//Controls panel, contains Button w/ action
Panel controls = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
controls.addComponent(new Button("Login", new Action()
{
public void doAction() {
MessageBox.showMessageBox(getOwner(), "Alert", "You entered the username " + usernameIn + " and password " + passwordIn + ".");
}
}));
addComponent(controls);
任何帮助都将不胜感激。我到处寻找信息,但实际上没有太多相关信息,这是我能找到的唯一一个最新的Java库,允许我制作终端应用程序。请注意:我知道上面的代码中没有任何内容可以处理输入的数据,我忽略了所有的尝试,因为它们导致了一页又一页的错误(这在使用错误的函数时是意料之中的)。我查看了Lanterna代码:
TextBox
有一个getText()
方法
作为一个想法:
Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
username.addComponent(new Label("Username: "));
TextBox userBox = new TextBox(null, 15);
username.addComponent(userBox);
addComponent(username);
// ... and later elsewhere
usernameIn = userBox.getText();
舒尔,您需要对userBox的引用,以便稍后在代码的其他地方获取内容
Lanterna还有一个ComponentListener接口,用于在值更改时响应:
Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
username.addComponent(new Label("Username: "));
TextBox userBox = new TextBox(null, 15);
userBox.addComponentListener(new ComponentListener() {
void onComponentValueChanged(InteractableComponent component) {
usernameIn = ((TextBox)component).getText();
}
});
username.addComponent(userBox);
addComponent(username);
这看起来更干净。在
TextBox
类中没有addComponent()
方法,Lanterna ver3.0.0-beta2
因此,在屏幕中使用readInput()
。
下面的示例表示当用户按enter键时,从文本框中获取文本
private Screen screen;
private TextBox textBox;
private final String emptyString = "";
...
public String getText() throws IOException {
String result = null;
KeyStroke key = null;
while ((key = screen.readInput()).getKeyType() != KeyType.Enter) {
textBox.handleKeyStroke(key);
// use only one of handleInput() or handleKeyStroke()
textBox.setText(textBox.getText());
}
result = textBox.getText();
textBox.setText(emptyString);
return result;