+ All Categories
Home > Documents > mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web...

mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web...

Date post: 20-May-2020
Category:
Upload: others
View: 1 times
Download: 0 times
Share this document with a friend
32
CS 1302 – Lab 7 To complete this tutorial, you must have the e(fx)clipse plugin to create JavaFX projects. To check, see the document on the Schedule named: eclipse_efx.docx. This is a tutorial on writing Graphical User Interfaces (Gui). There are 6 stages to complete this lab: Stag e Title Text Reference 1 Hello World Gui 14.3, 14.4, 16.2 2 Modularizing Gui Construction n/a 3 BorderPane Layout 14.10, 16.3, 16.6, 16.7 4 Programming an Event Handler 15.2-15.4 5 Other Layouts and Nesting Panes 14.10 6 RadioButtons and ComboBox 16.5, 16.8 To make this document easier to read, it is recommended that you turn off spell checking in Word: 1. Choose: File, Option, Proofing 2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…” Stage 1 - Hello World Gui In this stage we will build a Hello World Gui application using JavaFX. 1. Read (no action required) – Some basic definitions: Graphical User Interface (GUI) – A window that allows the user to interact with graphical icons (controls). A Gui is also called a form or window. Control – An element that is displayed on a GUI. For example, buttons, text boxes, labels are all controls as shown in the diagram on the right. Controls are sometimes called widgets. 1
Transcript
Page 1: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

CS 1302 – Lab 7

To complete this tutorial, you must have the e(fx)clipse plugin to create JavaFX projects. To check, see the document on the Schedule named: eclipse_efx.docx.

This is a tutorial on writing Graphical User Interfaces (Gui). There are 6 stages to complete this lab:

Stage Title Text Reference1 Hello World Gui 14.3, 14.4, 16.22 Modularizing Gui Construction n/a3 BorderPane Layout 14.10, 16.3, 16.6, 16.74 Programming an Event Handler 15.2-15.45 Other Layouts and Nesting Panes 14.106 RadioButtons and ComboBox 16.5, 16.8

To make this document easier to read, it is recommended that you turn off spell checking in Word:

1. Choose: File, Option, Proofing2. At the very bottom, check: “Hide spelling errors…” and “Hide grammar errors…”

Stage 1 - Hello World Gui

In this stage we will build a Hello World Gui application using JavaFX.

1. Read (no action required) – Some basic definitions:

Graphical User Interface (GUI) – A window that allows the user to interact with graphical icons (controls). A Gui is also called a form or window.

Control – An element that is displayed on a GUI. For example, buttons, text boxes, labels are all controls as shown in the diagram on the right. Controls are sometimes called widgets.

2. Establish a Workspace – Create a folder on your drive where you will put your lab or use an existing one.

3. Run Eclipse – As the program begins to run, it will ask you to navigate to the Workspace you want to use.

4. Create a JavaFX Project – We will create the Project for Lab 7.

a. Choose: File, New, Other, JavaFX, JavaFX Project, Next (as shown on the right).

b. Supply a project name, e.g. lab7_gibsond and then choose: Finish

1

Page 2: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

5. Expand the files in the Package Explorer. You will see the following items that were automatically created:

a. An application package.b. A Main class which is where you will write your code.c. A file named application.css which is a (empty) style sheet. Cascading Style

Sheets are very powerful and flexible technique for styling your GUI; however, we will not consider them in this course.

d. A JavaFX SDK folder and a build file, build.fxbuild neither of which we will use directly (but don’t delete them).

6. Open Main and run the program and observe the empty window that is displayed. Close the window.

7. Create Hello World Application – Open Main and do the following:

a. Copy the two lines below:

Label lbl = new Label("Hello World");root.setTop(lbl);

and paste into the start method directly below the second line of code as shown on the right.

b. Note the red X in the margin. Click it once.

c. In the pop-up menu double-click the item that says (as also shown on the right):

Import ‘Label’ (javafx.scene.control)

d. Verify that the import below has been added:

import javafx.scene.control.Label;

Note, you may have to do this at other places in this lab. For GUI components always choose the ones in the javafx… package.

e. Add this line below just above the call to: primaryStage.show():

primaryStage.setTitle("h.world app");

f. Run and observe the window.

2

Page 3: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

8. Read (no action required) – Let’s look carefully at the architecture of the Gui we built above. As shown in the figure below, The Stage contains a Scene which contains a BorderPane which contains a Label. Finally, the last line in the try block displays the Gui. (Note: figure below does not show the call to create the title on the window from Step 7.e above)

3

Page 4: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Stage 2 - Modularizing Gui Construction

In this stage we consider modularizing the creation of the Gui.

9. Read (no action required) – Almost always there is a lot of code to build a Gui so a good idea is to modularize this code. Instead of building the Gui in the start method, we will have the start method will call a method that builds and returns the Gui. Thus, in the start method we will replace these lines:

BorderPane root = new BorderPane();Label lbl = new Label("Hello World");root.setTop(lbl);

with this line:

BorderPane root = buildRoot();

Where buildRoot simply builds the Gui (a BorderPane) and returns it:

public BorderPane buildRoot() {BorderPane root = new BorderPane();Label lbl = new Label("Hello World");root.setTop(lbl);return root;

}

Note: we will explain the BorderPane class in Stage 3.

10. Do the following:

a. Close Main.b. Select Main.java in the Package Explorer and copy (Ctrl+c).c. Select the application package in the Package Explorer and paste (Ctrl+v).d. Provide the new name Main2.java.e. Open Main2 and add this method:

public BorderPane buildRoot() {BorderPane root = new BorderPane();Label lbl = new Label("Hello World");root.setTop(lbl);return root;

}

f. Replace the first three lines in the try block of the start method:

BorderPane root = new BorderPane();Label lbl = new Label("Hello World");root.setTop(lbl);

with:

BorderPane root = buildRoot();

g. Run and verify that the Hello World Gui appears

4

Page 5: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Stage 3 - BorderPane Layout

In this stage we consider the BorderPane class for laying out a Gui. We will consider event handling in the next stage.

11. Read (no action required) –

a. In the example we just considered, we noted that a BorderPane contains a Label as shown on the right. The highlighted line below shows how we accomplished this:

public BorderPane buildRoot() {BorderPane root = new BorderPane();Label lbl = new Label("Hello World");root.setTop(lbl);return root;

}

b. Actually, a BorderPane can contain 5 controls as shown in the figure1 on the right. The class defines methods to put a Control in each region:

setTop(…)setRight(…)setBottom(…)setLeft(…)setCenter(…)

c. Next, we will build a slightly more enhanced Hello World Gui using the top, center, and bottom regions of the BorderLayout.

12. Do the following:

a. Add these instance variables to the Main2 class (not the main nor start methods) as shown in the figure on the right.

TextField txfName;Button btnHellowWorld;TextArea txaMessage;

b. Click each red X to select the proper javafx package to import. Verify that these imports were added (or just copy these):

import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;

1 https://docs.oracle.com/javafx/2/layout/builtin_layouts.htm5

Page 6: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

c. Replace all the code in the buildRoot method with:

BorderPane root = new BorderPane();txfName = new TextField("Type your name");root.setTop(txfName);Button btnHelloWorld = new Button("Hello World");root.setCenter(btnHelloWorld);txaMessage = new TextArea();root.setBottom(txaMessage);return root;

Note the highlighted lines above that show how we compose the BorderPane (root) with the various controls.

d. Run and verify that the Hello World Gui appears as shown on the right. You can type a name in and press the button, but nothing happens, yet.

6

Page 7: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Stage 4 - Programming an Event Handler

In this stage we consider programming a simple event handler which specifies the code that will execute when, for instance, a button is pressed on the Gui.

13. Read (no action required) –

a. An event handler is code that is run when the user takes some action on a Gui, for example, when a button is pressed. There are at least 3 techniques to code event handlers. In this tutorial we will discuss just one, we will use an inner class. An inner class is a class inside another class. We will say a little more about these as we go along in this tutorial and discuss them more in class.

b. An overview of writing an event handler is:

i. Write a class that implements the EventHandler interface.ii. The EventHandler interface requires a handle method.

iii. Write the code that responds to the user’s interaction in the handle method.iv. Register the event handler with control (e.g. button) that the user will interact with.

c. For the application we have been working on, we will program the handle method so that it takes the name that the user supplied, composes a message with it, and then displays the message in a TextArea as shown in the figure below.

d. For this to work (i.e. so that the handle method is called when the button is pressed), we must register the event handler with the button with code like this:

btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());

e. Something very important to note is that the TextField (txfName) and TextArea (txaMessage) are defined as instance variables in the Main2 class. This is important because otherwise, the handle method could not access these variables. In other words, if we had defined them in the buildRoot method, they would have been local variables and thus not available in the handle method.

7

Page 8: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

14. Do the following:a. Add these two imports to the top of Main2:

import javafx.event.ActionEvent;import javafx.event.EventHandler;

b. Read (no action required) – We are about to add the event handler which we are implementing with an inner class. An inner class is a member of a class just like an instance variable or method. So, we will place it as shown highlighted below (since it is a member, of course it could be placed above buildRoot or below main, etc).

public class Main2 extends Application {...

public BorderPane buildRoot() {...

}

private class HelloWorldButtonEventHandler implements EventHandler<ActionEvent> {

...}

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

}}

c. Add the inner class below to Main2 in the position shown above, below buildRoot and above main.

private class HelloWorldButtonEventHandler implements EventHandler<ActionEvent> {

@Override public void handle(ActionEvent e) { String name = txfName.getText(); txaMessage.setText(name + ", Hello World!"); }}

d. Add the line of code below in the buildRoot method just below the line of code where you create the Button.

btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());

e. Run. Type in a name and press the button verifying that the Gui functions properly.

8

Page 9: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Stage 5 - Other Layouts and Nesting Panes

In this stage we consider several other useful layouts: GridPane, VBox, and HBox.

15. Read (no action required) –

a. A Pane is a way to layout a Gui. We saw earlier that a BorderPane allows the programmer to arrange the Gui into 5 regions: top, right, bottom, left, and center. JavaFx defines a number of other panes as shown in the class diagram on the right.

b. A GridPane is a container that holds UI controls and arranges them in a grid with columns and rows. It has an add method that accepts the control to add and the position on the grid to put the control. For example

grdPane.add(lblMsg, 0, 0);

places the label (lblMsg) in the upper left corner (column 0, row 0). Notice that the order is column, row, not the other way around! Thus, in general, the layout has regions identified as shown on the right.

c. As shown in the class diagram above, the Pane class is the superclass for the other layout classes. Next, we will build the Hello World app using a GridPane. To reduce the number of changes we need to make, we will replace this line in the start method:

BorderPane root = buildRoot();

With:

Pane root = buildRoot();

This should make sense because Pane is a superclass of BorderPane, GridPane, and others. Then we reprogram the the buildRoot method to use the GridPane.

16. Do the following:

a. Close Main2.

b. Select Main2.java in the Package Explorer and copy (Ctrl+c).

c. Select the application package in the Package Explorer and paste (Ctrl+v).

d. Provide the new name Main3.java.

e. Open Main3 and change the first line of the start method to:

Pane root = buildRoot();

Note, you will have a compile error because we don’t have an import for Pane. Click the red X to resolve it or add this import:

9

Page 10: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

import javafx.scene.layout.Pane;

f. Run and verify that the app still works correctly.

17. Next, we will write a method to build the app using a GridPane layout. Do the following:

a. Add this method to the Main3 class just below the buildRoot method:

public Pane buildGridGui() {GridPane pane = new GridPane();txfName = new TextField("Type your name");pane.add(txfName, 0, 0);Button btnHelloWorld = new Button("Hello World");btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());pane.add(btnHelloWorld, 0, 1);txaMessage = new TextArea();pane.add(txaMessage, 0, 2);return pane;

}

Note, you will have a compile error because we don’t have an import for GridPane. Click the red X to resolve it or add this import:

import javafx.scene.layout.GridPane;

b. Read (no action required) – Study the code above carefully, specifically, the three calls to pane.add(). Note that the controls are being placed in the first column in rows 1, 2, and 3, respectively.

c. Comment out the first line in the start method and then add the line below as shown on the right:

Pane root = buildGridGui();

d. Run and verify that the app still works correctly using the GridPane layout. It will appear very similar to the one using BorderPane except that the button is left justified.

e. Read (no action required) – At this point you are probably saying, “WTF?”. I’d have to agree, at least from a beginner’s perspective. The Gui’s we have created so far are probably not too appealing from an aesthetics point of view. What is the point of these different layouts? There are two aspects to designing a Gui. One is using an appropriate layout and the other is tweaking things so that they look professional. We will focus mostly on the former. However, first we show an example of how to put some spacing in the GridPane.

10

Page 11: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

18. Next, we will write a method to build the app using a GridPane that has spacing. Do the following:

a. Add this method to the Main3 class just below the buildGridGui method:

public Pane buildSpacedGridGui() {GridPane pane = new GridPane();pane.setHgap(10);pane.setVgap(10);pane.setPadding(new Insets(25, 25, 25, 25));txfName = new TextField("Type your name");pane.add(txfName, 0, 0);Button btnHelloWorld = new Button("Hello World");btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());

// GridPane.setMargin(btnHelloWorld, new Insets(0, 0, 0, 50));pane.add(btnHelloWorld, 0, 1);txaMessage = new TextArea();pane.add(txaMessage, 0, 2);return pane;

}

Note, you will have a compile error because we don’t have an import for Insets. Clicking the red X does not provide the correct solution. So, add this import:

import javafx.geometry.Insets;

Also note the highlighted lines above and the line commented out. We will briefly discuss them shortly.

b. Comment out the second line in the start method and then add the line below:

Pane root = buildSpacedGridGui();

c. Run and verify that the app still works correctly. Change some of the values in the highlighted lines above and/or uncomment the line that is commented out and try to tell what they are doing. For the record, I am not interested in you knowing what these methods do; I’m just briefly showing you that there are formatting options.

19. Next, we will write a method to build the app using a VBox layout. A VBox arranges the controls vertically in a single column, one on top of the other. An HBox is similar except that the arrangement is horizontal. Do the following:

a. Add this method to the Main3 class just below the buildSpacedGridGui method:

public Pane buildVBoxGui() {VBox pane = new VBox();txfName = new TextField("Type your name");pane.getChildren().add(txfName);Button btnHelloWorld = new Button("Hello World");btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());pane.getChildren().add(btnHelloWorld);txaMessage = new TextArea();pane.getChildren().add(txaMessage);return pane;

}

11

Page 12: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Note, you will have a compile error because we don’t have an import for VBox. Click the red X to resolve the error and make sure this import was added:

import javafx.scene.layout.VBox;

Also note the highlighted lines above. Adding controls to a VBox (or HBox) is a bit strange. We will not discuss it here.

b. Comment out the fourth line in the start method and then add the line below:

Pane root = buildVBoxGui();

c. Run and verify that the app still works correctly. The Gui looks very similar to the one when we used the (unspaced) GridPane.

20. Read (no action required) – One very useful concept is that we can nest panes: we can put panes inside of other panes. This provides for infinitely more layout flexibility and organization.

For example, consider the Gui shown on the right. There, we see that there is one main VBox (the green outline) which contains three HBox instances (the blue outlines). Finally, the top HBox contains a VBox and a GridPane.

In terms of a class diagram, this concept can be expressed this way:

In other words, a Pane can contain any number of (sub) Panes, and each Pane can contain any number of controls.

21. Next, we will build the Hello World app using nested panes as shown in the figure on the right. There, we see that we have an outer VBox that contains an HBox, a Button, and a TextArea. Do the following:

a. Add this method to the Main3 class just below the buildVBoxGui method:

12

Page 13: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

public Pane buildNestedGui() {VBox root = new VBox();root.setPadding(new Insets(25, 25, 25, 25));root.setSpacing(25);

HBox topPane = new HBox();topPane.setSpacing(25);Label lbl = new Label("Enter your name");txfName = new TextField("");topPane.getChildren().add(lbl);topPane.getChildren().add(txfName);

root.getChildren().add(topPane);

Button btnHelloWorld = new Button("Hello World");btnHelloWorld.setOnAction(new HelloWorldButtonEventHandler());root.getChildren().add(btnHelloWorld);

txaMessage = new TextArea();root.getChildren().add(txaMessage);

return root;}

Note, you will have a compile error because we don’t have an import for HBox. Click the red X to resolve the error and make sure this import was added:

import javafx.scene.layout.HBox;

b. Read (no action required) – Study the code above carefully. The highlighted lines show the top most pane (the VBox) and the nesting.

c. Comment out the fifth line in the start method and then add the line below:

Pane root = buildNestedGui();

d. Run and verify that the app still works correctly and appears similar to that shown above. You might need to stretch the window once it is displayed.

13

Page 14: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Stage 6 - RadioButtons and ComboBox

In this stage we consider several other useful controls: ComboBox (drop-down list), ToggleGroup, RadioButton.

22. Read (no action required) –

a. We will build the Gui shown below. Since the code can get long and messy, we will modularize even further by writing methods to build each of the components as shown below. For instance, we will write a method named nameEntryComponent (shown on the upper-left) that builds and returns an HBox that contains the Label and TextField. It is much easier to build and debug even a very modest sized Gui if we modularize.

b. Once these methods are written, we will write another method, buildGui to assemble these components. We will use a VBox to hold the various components as shown by the blue box in the figure below. The top row of the VBox will be an HBox as shown by the top green box in the figure below. The middle row will also be an HBox and the bottom row will simply be displayComponent (from the figure above).

14

Page 15: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

c. The code for buildGui will look like this:

VBox root = new VBox();

HBox topRow = new HBox();topRow.getChildren().add(this.nameEntryComponent());topRow.getChildren().add(this.buttonsComponent());

HBox middleRow = new HBox();middleRow.getChildren().add(this.salutationComponent());middleRow.getChildren().add(this.messageStyleComponent());

root.getChildren().add(topRow);root.getChildren().add(middleRow);root.getChildren().add(displayComponent());

23. Do the following:

a. Close Main3.

b. Select Main3.java in the Package Explorer and copy (Ctrl+c).

c. Select the application package in the Package Explorer and paste (Ctrl+v).

d. Provide the new name Main4.java.

e. Delete all code in Main4 except the package statement at the top

f. (Read, no action required) Next, we will add the code to build the Hello World app with just the controls we have used so far, i.e. not the ComboBox and RadioButtons. We will add the new controls in separate steps so that we can study the code more carefully. At the conclusion of the next step, the Gui will look as shown on the right (Similar to what we have done before).

g. Copy the code below and paste it into Main4 below the package statement.

Notes: The code below spans several pages, be sure and select it all. We’ve included all the imports we will need for subsequent steps. Thus, there will be a caution

indicator on some of them indicating that they are not needed. We will ignore that as they will be used eventually.

import javafx.application.Application;import javafx.stage.Stage;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.ComboBox;

15

Page 16: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

import javafx.scene.control.Label;import javafx.scene.control.RadioButton;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;import javafx.scene.control.ToggleGroup;import javafx.scene.layout.HBox;import javafx.scene.layout.Pane;import javafx.scene.layout.VBox;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.geometry.Insets;

public class Main4 extends Application {public static final int SPACING_BIG = 12;public static final int SPACING_SMALL = 2;protected TextField txfName;protected Button btnHellowWorld;protected TextArea txaMessage;

@Overridepublic void start(Stage primaryStage) {

try {Pane root = buildGui();Scene scene = new Scene(root,340,400);

scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

primaryStage.setScene(scene);primaryStage.setTitle("h.world app");primaryStage.show();

} catch(Exception e) {e.printStackTrace();

}}

public Pane buildGui() {

VBox root = new VBox();root.setPadding(new Insets(25, 25, 25, 25));root.setSpacing(SPACING_BIG);

HBox topRow = new HBox();topRow.setSpacing(SPACING_BIG);topRow.getChildren().add(this.nameEntryComponent());topRow.getChildren().add(this.buttonsComponent());

root.getChildren().add(topRow);root.getChildren().add(displayComponent());

return root;}

private Pane nameEntryComponent() {// Build name entry componentHBox name = new HBox();name.setSpacing(SPACING_SMALL);

16

Page 17: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

Label lblName = new Label("Name:");name.getChildren().add(lblName);

txfName = new TextField("");name.getChildren().add(txfName);

return name;}

private Pane buttonsComponent() {// Build buttons componentHBox buttons = new HBox();buttons.setSpacing(SPACING_SMALL);

Button btnShowMessage = new Button("Show Message");btnShowMessage.setOnAction(new ShowMessageEventHandler());buttons.getChildren().add(btnShowMessage);

return buttons;}

private Pane displayComponent() {// Build display areaVBox display = new VBox();display.setSpacing(SPACING_SMALL);

Label lblMessage = new Label("Message");display.getChildren().add(lblMessage);txaMessage = new TextArea();txaMessage.setPrefWidth(100);display.getChildren().add(txaMessage);

return display;}private class ShowMessageEventHandler implements EventHandler<ActionEvent> {

@Override public void handle(ActionEvent e) { String name = txfName.getText(); String msg = "Hello World, " + name;

txaMessage.setText(msg); }}

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

}}

h. Run and verify that the app still works correctly.

17

Page 18: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

24. Do the following:

a. Add this line as an instance variable just below the line declaring the TextArea:

protected ComboBox<String> cmbSalutation;

Note that a ComboBox is what we frequently call a drop-down list. In this case, the generic type parameter, <String> indicates that the “list” that will be displayed will be strings (it could hold images or other things).

b. Add the method below to Main4 (anywhere, but perhaps towards the bottom above main):

private Pane salutationComponent() {// Build message salutation componentVBox saluation = new VBox();saluation.setSpacing(SPACING_SMALL);

Label lblSalutation = new Label("Salutation");saluation.getChildren().add(lblSalutation);

cmbSalutation = new ComboBox<>();cmbSalutation.getItems().addAll("Mrs", "Ms", "Mr", "Dr");cmbSalutation.setValue("Ms");

saluation.getChildren().add(cmbSalutation);

return saluation;}

Notes: The first highlighted line adds the items to display in the ComboBox. The second highlighted line sets the item in the list that is initially displayed.

18

Page 19: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

c. Add these three lines:

HBox middleRow = new HBox();middleRow.setSpacing(SPACING_BIG);middleRow.getChildren().add(this.salutationComponent());

and this line:

root.getChildren().add(middleRow);

in the buildGui method at the two boxed locations shown in the figure on the right.

d. Replace the second line in handle method in the ShowMessageEventHandler inner class:

String msg = "Hello World, " + name;

with these to lines:

String salutation = cmbSalutation.getValue();

String msg = "Hello World, " + salutation + " " + name;

Note: The highlighted line above obtains the selection that the user has made ("Mrs", "Ms", "Mr", or "Dr") from the ComboBox and the second highlighted line shows us using this value in the message that is displayed.

19

Page 20: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

e. Run and verify that the app appears as shown on the right and works correctly.

25. Do the following:

a. Add this line as in instance variable just below the line declaring the ComboBox:

protected ToggleGroup tGrpStyleChoice;

Note: A ToggleGroup is a container that holds instances of RadioButton which we will add next.

b. Add the method below to Main4 (anywhere, but perhaps towards the bottom above main):

private Pane messageStyleComponent() {// Build message style componentVBox style = new VBox();style.setSpacing(SPACING_SMALL);

Label lbl = new Label("Message Style");style.getChildren().add(lbl);

tGrpStyleChoice = new ToggleGroup();

RadioButton rbShort = new RadioButton("Short");rbShort.setToggleGroup(tGrpStyleChoice);rbShort.setSelected(true);style.getChildren().add(rbShort);

RadioButton rbLong = new RadioButton("Long");rbLong.setToggleGroup(tGrpStyleChoice);style.getChildren().add(rbLong);

return style;}

Notes: The first highlighted line creates a RadioButton which displays the text: “Short”. The second highlighted line assigns the radio button to the ToggleGroup The third highlighted line selects this radio button for the initial display.

20

Page 21: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

c. Add this line:

middleRow.getChildren().add(this.messageStyleComponent());

in the buildGui method at the location shown in the figure on the right.

d. Replace the entire handle method in the ShowMessageEventHandler inner class with this version of the method:

public void handle(ActionEvent e) {String name = txfName.getText();String salutation = cmbSalutation.getValue();String style =

((RadioButton)tGrpStyleChoice.getSelectedToggle()).getText();String msg = "Hello World, " + name;

if(style.equals("Short")) {msg = "Hello world, " + salutation + " " + name + "!";

}else if(style.equals("Long")) {

msg = "It is a beautiful day, " + salutation + " " + name + "\n";msg += " I hope you have a 'hello world' kind of day!";

} txaMessage.setText(msg);}

Note:

The getSelectedToggle method in the first highlighted line above returns the Object that was selected in the ToggleGroup (tGrpStyleChoice), which must be cast to a RadioButton. Then, the getText method is called on the RadioButton to get the text (Short or Long) of the selected radio button.

Next, the style is used to determine whether a “Short” or “Long” message is composed and displayed.

21

Page 22: mypages.valdosta.edumypages.valdosta.edu/.../cs1302/labs/cs1302_lab_07.docx  · Web view2019-11-10 · – At this point you are probably saying, “WTF?”. I’d have to agree,

e. Run and verify that the app appears as shown on the right and works correctly.

You are done!

22


Recommended