javac -d . HelloEarthRiseMain.java
첫번째 JavaFX Program
On Christmas Eve in 1968 the crew of Apollo 8 entered lunar orbit for the first time in history. They were the first humans to witness an “Earthrise,” taking the magnificent picture shown in Figure 1-4. This image is dynamically loaded from this book’s web site when the program starts, so you’ll need to be connected to the Internet to view it.
In addition to demonstrating how to dynamically load images over the Internet, this example shows you how to use animation in JavaFX. Now it’s time for you to compile and run the program. We show you two ways to do this: from the command line and using NetBeans.
Compiling and Running from the Command Line
We usually use an IDE to build and run JavaFX programs, but to take all of the mystery out of the process we use the command-line tools first. Image Note For this exercise, as with most others in the book, you need the source code. If you prefer not to type the source code into a text editor, you can obtain the source code for all of the examples in this book from the code download site. See the Resources section at the end of this chapter for the location of this site.
Assuming that you’ve downloaded and extracted the source code for this book into a directory, follow the directions in this exercise, performing all of the steps as instructed. We dissect the source code after the exercise.
You’ll use the javac and java command-line tools to compile and run the program in this exercise. From the command-line prompt on your machine:
-
Navigate to the Chapter01/Hello directory.
-
Execute the following command to compile the HelloEarthRiseMain.java file.
-
Because the –d option was used in this command, the class files generated are placed in directories matching the package statements in the source files. The roots of those directories are specified by the argument given for the –d option, in this case the current directory.
-
To run the program, execute the following command. Note that we use the fully qualified name of the class that will be executed, which entails specifying the nodes of the path name and the name of the class, all separated by periods.
java projavafx.helloearthrise.ui.HelloEarthRiseMain
The program should appear as shown in Figure 1-4 earlier, with the text scrolling slowly upward, reminiscent of the Star Wars opening crawls.
Understanding the Hello Earthrise Program
Now that you’ve run the application, let’s walk through the program listing together. The code for the Hello Earthrise application is shown in Listing 1-1.
Listing 1-1. The HelloEarthRiseMain.java Program
public class HelloEarthRiseMain extends Application {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) {
String message
= "Earthrise at Christmas: "
+ "[Forty] years ago this Christmas, a turbulent world "
+ "looked to the heavens for a unique view of our home "
+ "planet. This photo of Earthrise over the lunar horizon "
+ "was taken by the Apollo 8 crew in December 1968, showing "
+ "Earth for the first time as it appears from deep space. "
+ "Astronauts Frank Borman, Jim Lovell and William Anders "
+ "had become the first humans to leave Earth orbit, "
+ "entering lunar orbit on Christmas Eve. In a historic live "
+ "broadcast that night, the crew took turns reading from "
+ "the Book of Genesis, closing with a holiday wish from "
+ "Commander Borman: \"We close with good night, good luck, "
+ "a Merry Christmas, and God bless all of you -- all of "
+ "you on the good Earth.\"";
// Reference to the Text
Text textRef = new Text(message);
textRef.setLayoutY(100);
textRef.setTextOrigin(VPos.TOP);
textRef.setTextAlignment(TextAlignment.JUSTIFY);
textRef.setWrappingWidth(400);
textRef.setFill(Color.rgb(187, 195, 107));
textRef.setFont(Font.font("SansSerif", FontWeight.BOLD, 24));
// Provides the animated scrolling behavior for the text
TranslateTransition transTransition = new TranslateTransition(new Duration(75000), textRef);
transTransition.setToY(-820);
transTransition.setInterpolator(Interpolator.LINEAR);
transTransition.setCycleCount(Timeline.INDEFINITE);
// Create an ImageView containing the Image
Image image = new Image ("http://projavafx.com/images/earthrise.jpg");
ImageView imageView = new ImageView(image);
// Create a Group containing the text
Group textGroup = new Group(textRef);
textGroup.setLayoutX(50);
textGroup.setLayoutY(180);
textGroup.setClip(new Rectangle(430, 85));
// Combine ImageView and Group
Group root = new Group(imageView, textGroup);
Scene scene = new Scene(root, 516, 387);
stage.setScene(scene);
stage.setTitle("Hello Earthrise");
stage.show();
// Start the text animation
transTransition.play();
}
}
Now that you’ve seen the code, let’s take a look at its constructs and concepts in some more detail.
Builders에서는 무슨 일이 생기나?
빌더는 프로그래밍의 선언적 스타일을 제공한다. set()메소드를 부르는 대신에 빌더 패턴은 목적 클래스를 어떻게 구성할지를 정의하는 Builder 클래스의 인스터스를 사용한다.
빌더가 JavaFX에서는 유명하지만 플랫폼으로 존속하는데 기술적 장애가 있음이 드러났다. 결과적으로 빌더를 퇴출하기로 결정하였다. 자바8에 빌더 클래스가 여저히 사용 가능하지만 앞으로는 더 이상 사용하지 않을 예정이다.
More information on the reason why Builder classes are not preferred anymore can be found in a mailing list entry by JavaFX Chief Architect Richard Bair at http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-March/006725.html. The bottom of this entry contains a very important statement: “I believe that FXML or Lambda’s or alternative languages all provide other avenues for achieving the same goals as builders but without the additional cost in byte codes or classes.”
This is what we will show throughout this book. Near the end of this chapter, we show a first example of a Lambda expression in our code. In Chapter 3, we show how SceneBuilder and FXML allow you to use a declarative way of defining a UI.
In the current example, we programmatically define the different components of the UI, and we glue them together. In Chapter 3, we show the same example using a declarative FXML-based approach.
The JavaFX Application
Let’s have a look at the class declaration in our first example:
public class HelloEarthRiseMain extends Application
This declaration states that our application extends the javafx.application.Application class. This class has one abstract method that we should implement:
public void start(Stage stage) {}
이 메소드는 자바FX 애플리케이션을 실행하는 환경에서 불리우는 메소드이다. 환경에 따라 자바FX 애플리케이션은 다른 방식으로 런칭된다. 개발자는start 메소드를 구현하고 제공된 Stage를 사용하요 UI를 만들면 된다.
In our command-line example, we launched the applications by executing the main method of the application class. The implementation of the main method is very simple:
public static void main(String[] args) {
Application.launch(args);
}
The only instruction in this main method is a call to the static launch method of the application, which will launch the application.
A JavaFX application always has to extend the javafx.application.Application class.