2017-10-16 43 views
0

我目前已将我的JavaFX代码设置为在蓝色和红色之间切换。程序运行时,带有文本“更改为红色”的按钮以蓝色文本显示。如果我点击按钮,它会变成红色文字写成的“更改为蓝色”。如果我再次点击它,则循环开始。我想要做的是应用相同的模式,但使用四种颜色。例如,我希望它开始于:如何恰当地获取文本的文本和颜色以在4种颜色之间切换/更改?

“更改为红色”,用蓝色文本编写。点击后,然后

“改变为绿色”,用红色文字写成。点击后,然后

“换成紫色”,用绿色文字写成。点击后,然后

“换成蓝色”,用紫色文字写成。

然后点击后再次启动周期结束:

“更改为红色”,写在蓝色文本。

等等,等等

这是我的代码有两种颜色:

public class FirstUserInput extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     Button btn = new Button(); 
     btn.setText("Change to Red"); 
     btn.setTextFill(Color.BLUE); 

    btn.setOnAction(e -> { 
     if (btn.getTextFill() == Color.RED) { 
      btn.setText("Change to Red"); 
      btn.setTextFill(Color.BLUE); 
     } else { 
      btn.setText("Change to Blue"); 
      btn.setTextFill(Color.RED); 
     } 
    }); 

谁能帮我改这个代码用四种颜色来工作?

+2

为什么你只是不扩展你有三个if语句? – Confuzing

+0

我试过了,它不起作用。顺序和颜色混合起来。 – Eatel

回答

1

那么,如果你想降低您有if-else语句,然后可以使用数组或枚举来容纳所有的选项编写和每个动作事件选择正确的一个类似的代码:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage; 

public class TestApp extends Application { 

    private int index = 0; 

    @Override 
    public void start(Stage primaryStage) { 
     Button btn = new Button(); 
     btn.setText("Change to Red"); 

     String allTexts[] = { "Change to Red", "Change to Blue", "Change to Green", "Change to Pink" }; 
     Color allColors[] = { Color.BLUE, Color.RED, Color.PINK, Color.GREEN }; 

     btn.setOnAction(e -> { 

      index++; 
      if(index >= allTexts.length) { 
       index = 0; 
      } 

      btn.setText(allTexts[index]); 
      btn.setTextFill(allColors[index]); 

     }); 

     VBox box = new VBox(); 
     box.getChildren().add(btn); 

     primaryStage.setScene(new Scene(box)); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 

那么以上的作品,当变化顺序我希望你在找什么。

+0

它说找不到变量索引。我现在正试图弥补这一点。如果你能帮忙,请告诉我如何解决这个问题。 – Eatel

+0

@Eatel正如我在代码中指出的那样,您需要将索引变量定义为全局像'private int index = 0;'无论如何,我会更新我的答案给出一个完整的示例。 – JKostikiadis

+0

它不起作用。颜色与文字不符。当它应该变成蓝色时变成粉红色,反之亦然。 – Eatel