【问题标题】:Assign values to a text field based on a buttons text根据按钮文本为文本字段分配值
【发布时间】:2019-02-20 05:32:23
【问题描述】:

我正在创建一个程序,它接受一个输入文件,解析该信息并根据该信息构建一个 GUI 计算器。目前该程序运行良好,除了我在按钮上实现 ActionListener 时应该将文本字段设置为按钮 getText() 方法的值。

我使用 for 和 while 尝试了几种不同的循环结构,但我实现的所有循环结构都没有找到 where i 或 counter 等于从 numPad.getText() 解析的 int 或为所有的返回 0按钮。

我在测试时遇到的问题是变量 i 从不匹配 numPoint。从逻辑上讲,我的方法是减少 i 以便循环将继续寻找匹配项,但从不这样做。测试输出声明无限循环“-1”代表 i,“7”代表 numPoint。请注意,numPad 数组不是按顺序排列的,而是元素如下 {7, 8, 9, 4, 5, 6, 1, 2, 3, 0}。

我意识到这个循环在逻辑上可能不正确,但我很难找到可行的解决方案。我想避免硬编码 if 语句(例如 i == Integer(parseInt.numPad[0].getText()),这会起作用。

这是创建新按钮并将它们添加到数组中的循环,根据从输入文件的值创建的列表设置文本并添加 ActionListener。

for (int i = 0; i < run.buttons.size(); i++) {
        numPad[i] = new JButton();
        numPad[i].setText(run.buttons.get(i));
        numPad[i].addActionListener(new ButtonActionListener());
        panel1.add(numPad[i]);
    }

这是最近一次尝试创建一个应该进行分配的循环。

public static class ButtonActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        int i;
        int numPoint;
        for (i = 0; i < numPad.length; i++) {
            numPoint = Integer.parseInt(numPad[i].getText());

            if (i == numPoint) {
                //Match, assign
                System.out.println("works");
                break;
            } else {
                //Decrement and continue
                i--;
                System.out.println("test statement" + i + " " + numPoint);
                continue;
            }
        }

    }       
}

【问题讨论】:

  • 另见calculator example。它使用ScriptEngine 来评估文本字段中的表达式。

标签: java swing user-interface


【解决方案1】:

有几种方法可以做到这一点,但让我们从基础开始

for (int i = 0; i < run.buttons.size(); i++) {
        numPad[i] = new JButton();
        numPad[i].setText(run.buttons.get(i));
        // You don't "have" to do this, as the action command defaults
        // to the text of the button, but this is away to provide some
        // kind of identifier to the action which might be
        // different from the text
        numPad[i].setActionCommand(run.buttons.get(i))
        numPad[i].addActionListener(new ButtonActionListener());
        panel1.add(numPad[i]);
}

然后在你的ActionListener...

public static class ButtonActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        int numPoint = Integer.parseInt(command);
        // Perform what ever action you need
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2017-03-04
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多