有6个按钮,每个按钮都有一个OnMouseEntered处理程序,可以将Button的文本更改为“Click Me!”。还有一个OnMouseExited处理程序,可以将Button的文本更改回原始文本。
是否有任何方法可以使代码尽可能干净?如何?非常感谢你! 有大量重复的代码:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class MyGUI extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
HBox root = new HBox();
VBox vb = new VBox();
Button[] btn = new Button[6];
for (int i = 0; i < 6; i++) {
btn[i] = new Button("Button" + (i + 1));
}
vb.getChildren().addAll(btn);
root.getChildren().addAll(lv, vb);
btn[0].setOnMouseEntered(e -> {
btn[0].setText("Click Me!");
});
btn[1].setOnMouseEntered(e -> {
btn[1].setText("Click Me!");
});
btn[2].setOnMouseEntered(e -> {
btn[2].setText("Click Me!");
});
btn[3].setOnMouseEntered(e -> {
btn[3].setText("Click Me!");
});
btn[4].setOnMouseEntered(e -> {
btn[4].setText("Click Me!");
});
btn[5].setOnMouseEntered(e -> {
btn[5].setText("Click Me!");
});
btn[0].setOnMouseExited(e -> {
btn[0].setText("Button1");
});
btn[1].setOnMouseExited(e -> {
btn[1].setText("Button2");
});
btn[2].setOnMouseExited(e -> {
btn[2].setText("Button3");
});
btn[3].setOnMouseExited(e -> {
btn[3].setText("Button4");
});
btn[4].setOnMouseExited(e -> {
btn[4].setText("Button5");
});
btn[5].setOnMouseExited(e -> {
btn[5].setText("Button6");
});
Scene MScene = new Scene(root, 800, 600);
primaryStage.setTitle("My Button");
primaryStage.setScene(MScene);
primaryStage.show();
}
}
答案 0 :(得分:0)
根据要求,有各种解决方案,例如: G:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MyGUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
HBox root = new HBox();
VBox vbox = new VBox();
Button[] buttons = new Button[6];
for (int i = 0; i < 6; i++) {
String text = "Button" + (i + 1);
Button button = new Button(text);
button.setOnMouseEntered( e -> button.setText("Click Me!"));
button.setOnMouseExited( e -> button.setText(text));
buttons[i] = button;
}
vbox.getChildren().addAll(buttons);
root.getChildren().addAll(vbox);
Scene scene = new Scene(root, 800, 600);
primaryStage.setTitle("My Button");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}