简体   繁体   English

等待TextField输入,然后继续执行代码

[英]Wait for TextField input, before continuing with the code

I have a Graphical User Interface that has a TextField , my code looks as following: 我有一个具有TextField的图形用户界面,我的代码如下所示:

int port = 0;
    try{
    port = Integer.parseInt(frame.textfieldInput.getText());
    }
    catch(NumberFormatException npe)
    {
        System.out.println("Error! parse exception");
    }

    System.out.println("The Port is " + port); //is 0

I have to assign the value '0' to port, because otherwise the code wont compile, because the variable wouldn't be initialized. 我必须将值'0'分配给端口,因为否则该代码将无法编译,因为该变量不会被初始化。

Because the TextField is empty at the beginning of the Program, getText() wont get a value, which is why port stays '0'. 由于TextField在程序开始时为空,因此getText()不会获取值,这就是为什么端口保持为“ 0”的原因。

Is there any way to wait for the input before the code continues? 在代码继续之前,有什么方法可以等待输入吗?

Found a solution, this is how I solved it: 找到了解决方案,这就是我解决的方法:

I created a global variable outside of my ActionListener : 我在ActionListener之外创建了一个全局变量:

public String value = "";
public void createInput() {
    buttonInput.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            value = textfieldInput.getText();

        }

    });
}

named 'value'. 命名为“值”。

in my public static void main(String[] args) I declared the following: 在我的public static void main(String[] args)我声明了以下内容:

while(frame.value.equalsIgnoreCase(""))
{
    try
    {
        System.out.println("waiting...");
        Thread.sleep(1000);
    }
    catch(InterruptedException ie)
    {
    System.out.println("interrupted");
    }
}

I just have to clear the variable 'value' everytime I used it, so it is empty again for future uses. 我每次使用时都只需要清除变量“值”,因此它再次为空以供将来使用。

I tis not the best way to solve it, but it worked for me. 我不是解决它的最佳方法,但是它对我有用。

Below code may give you some idea to more efficient way to get value on focus lost. 下面的代码可能会给您一些思路,让您更有效地失去关注的价值。

JFrame frame = new JFrame();
frame.setSize(50, 50);
TextField field = new TextField();
field.addFocusListener(new FocusListener() {

    @Override
    public void focusLost(FocusEvent e) {
        // continue from here
        System.out.println(field.getText());
    }

    @Override
    public void focusGained(FocusEvent e) {
        // TODO Auto-generated method stub

    }
});
frame.getContentPane().add(field);
frame.setVisible(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM