java - 根据按钮文本为文本字段分配值

标签 java swing user-interface

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

我尝试了使用 for 和 while 的几种不同的循环结构,但是我实现的所有循环结构都没有找到 i 或计数器等于从 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;
            }
        }

    }       
}

最佳答案

有多种方法可以实现此目的,但让我们从基础开始

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
    }

关于java - 根据按钮文本为文本字段分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52348301/

相关文章:

java - TCP线程服务器/客户端

iphone - UIImagePickerController allowedEditing=YES 问题

java - 多线程运行速度比单进程慢

java - Spring Data Mongo - 如何映射继承的 POJO 实体?

java - MouseListener 无法识别第一次点击

java - 创建一个窗口 - 但按钮布局错误

javascript - 如何设置剑道网格列中超链接的数字格式

java - SmartGwt 为 Selectitem 选择所有选项

java - 将 Apache POI 与 GraalVM native 镜像结合使用 - 来自 XMLBeans 的 ClassCastException

java - 在不同的 JPanel 中显示组合框 java