java - 如何在 while 循环中获取新的操作命令

标签 java events while-loop actionlistener

我编写了一个程序,当您单击按钮时,它会向 JLabel 添加一个数字。我有 4 个不同的按钮。

问题是我做了一个 while 循环,每次单击按钮时它总是添加相同的数字

public class GUI extends JFrame {

    private JLabel counter;
    private JButton val5;
    private JButton val10;
    private JButton val25;
    private JButton val50;

    public GUI() {
        super("The Title");
        setLayout(new FlowLayout());

        counter = new JLabel("This is the counter: 0");
        val5 = new JButton("5");
        val5.setActionCommand("5");
        val10 = new JButton("10");
        val10.setActionCommand("10");
        val25 = new JButton("25");
        val25.setActionCommand("25");
        val50 = new JButton("50");
        val50.setActionCommand("50");
        add(counter);
        add(val5);
        add(val10);
        add(val25);
        add(val50);

        HandlerClass handler = new HandlerClass();
        val5.addActionListener(handler);
        val10.addActionListener(handler);
        val25.addActionListener(handler);
        val50.addActionListener(handler);
    }

    private class HandlerClass implements ActionListener {
        int sum = 0;

        public void actionPerformed(ActionEvent event) {

            while (sum < 1000) {
                String action = event.getActionCommand();
                int numberInt = Integer.parseInt(action);

                switch (numberInt) {
                    case 5:
                        System.out.println("add 5");
                        break;
                    case 10:
                        System.out.println("add 10");
                        break;
                    case 25:
                        System.out.println("add 25");
                        break;
                    default:
                        System.out.println("add 50");
                        break;
                    //counter.setText(String.valueOf(action));
                }
            }
        }
    }
}

最佳答案

这是您的代码的工作示例。请不要仅仅将其用作解决方案,而是要向您展示当前的问题所在。

private JLabel counter;
private JButton val5;
private JButton val10;
private JButton val25;
private JButton val50;

// a JLabel can only hold Strings, so you loose the int value. Therefore 
// you could hold the value in a separate variable and just update the label
// when you have a new value.
private int sum;   

public GUI() {
    super("The Title");
    setLayout(new FlowLayout());
    sum=0;                         // first we start at 0

    counter = new JLabel("This is the counter: 0");
    val5 = new JButton("5");
    val5.setActionCommand("5");
    val10 = new JButton("10");
    val10.setActionCommand("10");
    val25 = new JButton("25");
    val25.setActionCommand("25");
    val50 = new JButton("50");
    val50.setActionCommand("50");
    add(counter);
    add(val5);
    add(val10);
    add(val25);
    add(val50);

    HandlerClass handler = new HandlerClass();
    val5.addActionListener(handler);
    val10.addActionListener(handler);
    val25.addActionListener(handler);
    val50.addActionListener(handler);
}


class HandlerClass implements ActionListener {      
    // you may even hold the sum variable here, but this class is supposed to be a listener, not a model for your view. 

    public void actionPerformed(ActionEvent event) {

        if (GUI.this.sum < 1000) {    // your previous while loop was infinite. 
        // I don't know if you wanted to count to 1000 once the user clicks a button or just add the number. Anyway. 
        // GUI.this.sum will access the sum variable in the current GUI instance and then we check if the sum is smaller 1000. If so, we add the input value
            String action = event.getActionCommand();
            int numberInt = Integer.parseInt(action);
            // the switch is actually not necessary unless you plan to do more with it
            switch (numberInt) {
                case 5:
                    System.out.println("add 5");
                    break;
                case 10:
                    System.out.println("add 10");
                    break;
                case 25:
                    System.out.println("add 25");
                    break;
                default:
                    System.out.println("add 50");
                    break;
                //counter.setText(String.valueOf(action));
            }
            sum+=numberInt; // first we add the value from the button to the global sum
            counter.setText("This is the counter: "+sum); //then we update the text from the label with the new value
        }
    }
}

该示例可以运行,但不是很干净。重用相同的 ActionListener 是一种很好的方法,但转换操作命令来获取值有点古怪。

您可以这样做,而不是使用 setActionCommand("5"); 和完整的 ActionListener 实现:

val5.addActionListener((e) -> {    // this is the lambda-approach to write the ActionListener implementation (since the interface has only one method, you can just write your method here)
     if(sum<1000){      // here you can access the sum variable directly
         sum+=5;        // update its value
         counter.setText(".....");  // set the new label text
     }
});

虽然您必须为每个按钮执行此操作,但这样更易于维护。

更简洁的方法是在单独的方法中编写计算代码,如下所示:

private void add(int number) {
    if (sum < 1000) {
        sum += number;
        counter.setText(".....");
    }
}

然后将 Action 监听器注册到按钮,如下所示:

val5.addActionListener((e) -> add(5));   //for val10 you call add(10) and so on...

关于java - 如何在 while 循环中获取新的操作命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57628286/

相关文章:

java - 通过小部件中的按钮触发事件

javascript - 使用 web3-core-promievent 创建一个返回 PromiEvent 的函数

c - 仅使用 while 和 if 对数组进行排序

java - Java中while循环的Big-O

java客户端应用程序 session 恢复

java - 在 Java 中抛出多个异常

java - 将 java 代码转换为 python,IDE 建议?

java - 使用随机库 Java 进行播种产生相同的结果

C++ 部分互斥锁/临界区锁

php - 以正确的方式使用 while 和 foreach 显示 mysql