java - 每次按下按钮时呈现颜色(lambda 表达式)

标签 java button lambda

每当按下按钮时,我想设置某种颜色。现在用户可以写一个 int 并显示相应的颜色(无需每次都键入相应的 int)。 不过我想改变这一点。每次用户单击按钮时,都会显示下一种颜色,但我不知道如何重写代码。 我尝试了 do while 和 for 循环,但我在 lambda 中使用的变量有问题表达式(显然应该是最终的)?

board.setButton2Text("Select"); 
board.setButton2Action(() -> {
    int c = 0;
    while(!(c > 0 && c < 7)) {
        try {
            c = IO.inputInt("Type an int ranging from 1 to 6");
        } catch (RuntimeException e) {
            continue;
        }
    }
    currentCode.setColor(selectedCircle, c);
    drawCode(X_START, Y_START + LINE_SPACING * (6 - currentTry), currentCode);
});

现在看起来像这样

enter image description here

最佳答案

更改对按钮点击使用react的代码。该代码应该:

  1. 获取当前设置的颜色。
  2. 给该颜色编号加一。
  3. 如果新数字超过限制 (0-7),则循环。
  4. 将颜色设置为新的色号。

像这样:

board.setButton2Action( () -> {
        // On each click of the button, rotate to the next color in a sequence of colors numbered 0-7. 
        int c = currentCode.getColor( … ) ; // TODO: Add assertion tests to verify you get back a valid value as expected.
        c = ( c + 1 ) ;  // Increment the color.
        if( c == 8 ) {  // If past the limit…
            c = 0 ;     // …go back to first number.
        }
        currentCode.setColor( selectedCircle , c ) ;
        drawCode( X_START , Y_START + LINE_SPACING * ( 6 - currentTry ) , currentCode ) ;
    }
);

我不认为您的 lambda 在这里会是个问题。更改为我在此处显示的代码不会涉及 lambda 范围之外的任何其他对象。

关于java - 每次按下按钮时呈现颜色(lambda 表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176806/

相关文章:

python - 使用 lambda 表达式查找列表中每两个相邻元素之间的差异?

c++ - 如何避免捕获的成员在 C++11 的 lambda 表达式中被任意表达式初始化?

c++ - 将 lambda 表达式转换为函数指针

java - GUI JButton,如何将按钮(问题)分配给答案

java - 使用 spring Autowiring 从 java 中的静态类调用非静态方法?

java - volatile 变量与实例变量的功能

c# - Aspx Web 窗体命令参数

java - 无法在 Spark Executor 中创建 DynamoDB 客户端

android - 在android中点击一个按钮显示 map

css - 等宽垂直按钮