首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Java中通过按钮创建输入值的序列?

如何在Java中通过按钮创建输入值的序列?
EN

Stack Overflow用户
提问于 2016-03-15 23:17:43
回答 1查看 74关注 0票数 1

我想写程序谁在t1(TextField)中输入用户想要输入的数字,并通过b1(按钮)确认。在t2(TextField)中,用户提供第一个值并通过b2(按钮)输入,在next time (下一次)中用户提供第二个值,然后再次通过b2(按钮)输入。它发生的次数如此之多,因为高值是n(从第一个侦听器)。

我必须如何更改程序代码才能做到这一点?

现在,当我给t2第一个值并按下按钮时,b2仍然被按下,用户不能做任何事情。

代码语言:javascript
运行
复制
final AtomicInteger n = new AtomicInteger();
ActionListener lis5 = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        String a = t1.getText();
        n.set(Integer.parseInt(a));
    } 
};
b1.addActionListener(lis5); 

ActionListener lis6 = new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        //String b = t2.getText();     ??
        //n.set(Integer.parseInt(b));  ??

        int nn = n.get();
        int [] tab = new int[nn];
        for(int i=0;i<nn;i++){
            tab[i] = in.nextInt();
        }
    } 
};
b2.addActionListener(lis6);
EN

回答 1

Stack Overflow用户

发布于 2016-03-15 23:23:53

首先,去掉ActionListener中的for循环。For循环适用于线性控制台程序,这些程序使用扫描仪输入数据,但不适用于事件驱动的图形用户界面。这里使用计数器int变量代替for循环,该变量在ActionListener中递增,用于帮助您决定将数据放在何处。还要将整数数组从ActionListener中取出并放入类中,这样它就可以对类的其余部分可用。在伪代码中:

代码语言:javascript
运行
复制
in the class
    int array declared here BUT not initialized here.

    first Actionlistener
        get total count value
        initialize array using this value
    end first action listener

    second ActionListener
        int counter variable set to 0.
        action performed method
            if counter < total count
                get value from text field
                convert it to an int
                place value into intArray[counter]
                increment counter
            end if
        end action performed
    end second ActionLisener    
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36015282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档