patternjavaMinor
Hello parallel world
Viewed 0 times
helloworldparallel
Problem
I'm introducing someone to JavaFX. It still feels relatively new and I don't take being someone's first exposure to something lightly. I want to know if there's anything I'm doing unconventionally, inefficiently, or just plain oddly in this code? Although it is relatively simple, If fresh eyes could discern something unaccounted or discern a should-be inclusion, I'd be remiss not to illuminate self before attempting to do so for another.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Hello extends Application {
Scene scene;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
TextField entry = new TextField();
entry.setPromptText("Enter your name");
Button hello = new Button("Greeting");
hello.setOnAction(e -> greet(entry));
hello.setDefaultButton(true);
hello.setTooltip(new Tooltip("Click me!"));
HBox layout = new HBox();
layout.getChildren().addAll(entry, hello);
layout.setPadding(new Insets(2, 12, 2, 12));
scene = new Scene(layout);
stage.setScene(scene);
stage.setTitle("Welcome to JavaFX");
stage.show();
hello.requestFocus();
}
public void greet(TextField entry) {
String name = entry.getText();
Label label = name.isEmpty() ? new Label("Hello user!") : new Label("How's it going, " + name + "?");
scene.setRoot(label);
}
}Solution
Pretty neat. I think this:
Could be neater like this:
Actually... what changes depending on the result
I'd probably rename
Label label = name.isEmpty() ? new Label("Hello user!") : new Label("How's it going, " + name + "?");Could be neater like this:
Label label = name.isEmpty()
? new Label("Hello user!")
: new Label("How's it going, " + name + "?");Actually... what changes depending on the result
name.isEmpty() isn't the label itself, but its content.String greeting = name.isEmpty()
? "Hello user!"
: "How's it going, " + name + "?";
Label label = new Label(greeting);I'd probably rename
label to greetingLabel, too.Code Snippets
Label label = name.isEmpty() ? new Label("Hello user!") : new Label("How's it going, " + name + "?");Label label = name.isEmpty()
? new Label("Hello user!")
: new Label("How's it going, " + name + "?");String greeting = name.isEmpty()
? "Hello user!"
: "How's it going, " + name + "?";
Label label = new Label(greeting);Context
StackExchange Code Review Q#93057, answer score: 8
Revisions (0)
No revisions yet.