OOPS Unit5
OOPS Unit5
interface. ‘This interface defines the It is an instance of the Event ef extends Event> denotes that Tis a generic type that is common behavior for all handlers. a subtype of Event. * The EventHandler object handle andler). interface contains the handle ave to write the handler class fx.event EventHandler class in er must be registered with the event source object using the method source.setOnAction(h « The EventHandler(ActionEvent) method for g the action event. We h that must override this processin; the event. He method to respond to our application program race we must import javalie. 5-12 __JavaFX Event Handling, Controls Object Oriented Programming a 24 Compre The event Class hierarchy is hown below - WindowEvent ‘ActionEvent MoyseEvent | ! FEE eee erence EventObject Event | inputévent_ kX—| KeyEvent | t Fig. 5.2.1 Event class hierarchy * There are user actions that are associated with some source objects. For these actions particular event is fired. The JavaFX associate some setOnXXX methods for registering these events. The list of such user actions, source objects and setOnXXX methods are enlisted in the following table. User Action | Source Object | Event Type Event Registration Method a] Fired Click button Button _| ActionEvent _| setOnAction(EventHandler ) Enter text in TextField | ActionEvent | setOnAction(EventHandler ) textfield os Click radio | RadioButton | ActionEvent setOnAction(EventHandler ) button for check or uncheck Check or Checkbox | ActionEvent setOnAction(EventHandler ) uncheck checkbox ‘ T { Select an item -ActionEvent * Java makes use of delegation b. ° sed. i : i ee eee #sed’ model for event handling and registration, This model is TECHNICAL PUBLICATIONS® «en oan=z Oriented Programming cee x je JavaFX Event Han, ROMS aa ent Handling, Contos and Components ‘SourceClas Trager se EventHandler . It contains searia handle0 function for processing the event. @) The handler object is registered by the source object. The registration methods depend on the event type. For ActionEvent, the method is setOnAction. For a mouse pressed event, the method is setOnMousePressed. For a key pressed event, the method is setOnKeyPressed. eal For example Button button = new Button(“Click Me"); //Event object is button button.setOnAction(new EventHandler () //Bvent registration { public void handle(ActionEvent event) } Following is a complete JavaFX program, that displays the message on clicking the button. Thus button click event is handled in the following program. Programming Example 1 package myjavafxapplication; el is import javafx.application. Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox, import javafx.event.ActionEvent; TECHNICAL PUBLICATIONS® - an up-thrust for krowledye et ———=—Object Oriented Programming 5-15 JavaFX Event Handling, Controls and Components, On clicking the above button, we get following message in the output window nottcations mn kaa run) > Ne base SOK. Package will use syaven JAE a 2g Copying 12 fires to eg 1912 ean 2s \MyJavaFXApplication\dist\ runt721591213 tere Mapp licavion\aise\zunl721831213\Myzavel ication. jar using platform Button is clicked!! 1 72.1621219\MyTavaFEApels 5.3] Handling Key and Mouse Events §.3.1] Handling Mouse Event Mouse event is fired when the mouse button is pressed, released, clicked, moved or dragged on the node. Following table shows the user actions and associated event handling activities - User) Source | Event Type Event Registration Method Action | Object Fired ioLse setOnMousePressed(EventHandler ) Pressed Mouse Node, | Mousetivent | setOnMouseReleased(EventHandler ) Clicked Mouse setOnMouseMoved (EventHandler ) Moved 5 Neri setOnMouseDragged (EventHandler ) Dragged Mauge | setOnMouseEntered (EventHandler ) entered Z Maus setOnMousebxited(EventHandler ) Key Released setOnKeyReleased(EventHandler ) Node, | KeyEvent Key typed ed. setOnKeyTyped(EventHandler ) recognizing the keyboard events we use KeyEvent class. Various methods of KeyEvent | For class are as described in the following table. Method Description String getCharacter() Returns the character associated with the key pressed. KeyCode getCode() Returns the key code associated with the key in the event, _ String getText() Returns the string describing the key code. boolean isAltDown() It returns true if the ALT key is down. boolean isControlDown() _ | It returns true if the Control key is down, oe boolean isMetaDown() boolean isShiftDown() TECHNICAL PUBLICATIONS® - an up-thrst for knowledgeObject Oriented Programming The key codes returned by the getCode() method are constants. These constants are enlisted in the following table - 5-20 [Een Aaecweniey ae HOM wy The Home key Be END oe The End key CONTROL The control key SHIFT The shift key PAGE_UP The page up key PAGE_DOWN The page down key UP. The Up key DOWN The Down key LEFT The left arrow key RIGHT The right arrow key BACK_SPACE The backspace tree CAPS The caps lock key ESCAPE The escape key ENTER The enter key TAB The tab key NUM_LOCK The num lock key Otoo The keys from 0 to 9 AtoZ The letter keys from A to Z Following is a simple keyboard event ha the output window. Programming Example JavaFX Event Handling, Controls and Components Package myjavafxapplication; import Javafs application. Application; import javatx, ‘event. EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import Javafx.scene.input MouseEvent: TaProgram Explanation : 22 fava Event Handi n above code, Text node. As we want bold,arial ang . (1) For displaying the character typed we have set the font size of 30 px, we use setFont method. (2) Then the keybpard event is set using the lambda function text.setOnKeyPressed(e->{ text.setText(e.getText()); ye: Due to this event, the key being pressed is displayed. 5.4] Controls jow based application. ® The graphical User Interface (GUI) is an essential part of any wind 1m is possible with the help of User © The interaction between user and the application progra Interface (UI) controls that are placed on the screen. «JavaFX allows its developer a rich set of UL controls. Some of the most commonly used UL Controls are enlisted in the following table. Control Description Label Label is a control that displays simple text on the screen. It is generally used to describe the other user controls. | Button Button component is used to control specific function of the application. RadioButton | The radio button is used to provide the choices to the user. The radio button can be selected or deselected, CheckBox ‘The checkbox is used to provide various choices to the user. The check box can be checked(True) or unchecked( False) TextField For getting the input from the user, the textfield is provided. Textarea This control allows the user to enter the multiple line text. ComboBox | This control displays the list of items out of which user can select at the most one item, ListView This control displays the list of items out of which user can select one or multiple items from the list Slider ‘ This control is used to display a continuous or discrete range of valid numeric choices and allows the user to interact with the control. | Let us now learn and understand how controls, to create simple JavaFX programs that use these UIY 1 Oriented Programming 5-23 _JavaFX Event Handling, Controls and Components and a f User ed UL n \ be ne ple onject 8 [ade ‘The label control displays simple text on the screen. «Its main purpose is to describe other components such as textfield, textarea, radio button and. + For using this control the package javafx.scene.control.Label need to be imported. ‘© The constructors used for using Label control is Label() : This creates an empty label. Label(String txt) : This creates a label with supplied text. Label(String txt, Node graphics) : It creates a label with supplied text and graphics © Programming Example package MyJavaFXApplication; import javafx.application Application; import static javafx.application. Application launch; import javafx.event. ActionEvent; import javafx.event. EventHandler, import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.control Label; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage) { ‘StackPane root=new StackPane(); Label L=new Label("User Name"); Scene scene = new Scene(toct, 260, 250); i .ada(L); root.getChildren().add(L); : ryStage.setTitle(‘Label Demo’); imal S fene(scene); primaryStage.setSe primaryStage. show(); Une static void main(Stringl] args) { Jaunch(args); } i 7 up-t eof PUBLIATIONS® pt rust or know? | _ mmeEETE,Object Oriented Programming 524 __JovaPX Event Handling, Contos and Componens y | EE Program Explanation : In above program, (1) We have created StackPane so that the Label control can be arranged on top just like a stack. The stackPane is a used to decide the layout of the screen. This is named as root node. (2) Then we have created one label “User Name" using the Label constructor, @) These controls must be contained in‘a scene. Hi node using Scene constructor. This scene is setScene method. fence a scene is prepared by adding a root then attached to a primaryStage using created using following code Click Here"); * For using the button contr Programming Example Package MyJavaFXApplication; TECHNICAL PUBLICATIONS® -an p-thrust for knowiecianay ents object Ortented Programm 5 25x Event Handing, Controls and Components SSR Hotling, Controls and Components ‘layout StackPane; import javatx stage stage, Toot.getChildren()add(B); PrimaryStage.setTitle("Button Demo’) PrimaryStage.setScene(scene); primaryStage.show/(); } public static void main(String] args) { launch(args); } }Le Object Oriented Programming 7 5-26 __ JavaFX Event Handling, Controls and Components Checkbox Checkbox is used to provide more than one choices at a time. For us ng checkbox in our application program, we must insert following line in the program at the beginning - import javafx.scene.control.Checkbox ‘The checkbox can be created using following statement CheckBox ch=new CheckBox(“Label Name"); The checkbox is selected true by using the method, setSelected(“true”) Following program shows how to create checkbox. Programming Example package MyJavaFXApplication; import java io FileInputStream; import javafx.application. Application; import static javafx.application. Application launch; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control. CheckBox; import javafx.scene layout. HBox; import javafx.stage Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage)throws Exception { HBox root=new HBox(); Label L=new Label('Select your favorite color: " CheckBox ch1=new CheckBox("Red"); CheckBox ch2=new CheckBox("Blue"); CheckBox ch3=new CheckBox("Green’ CheckBox ch4=new CheckBox("Yellow"); Scene scene = new Scene(root, 400, 100); root.getChildren().addAll(L,ch1,ch2,ch3,ch4); primaryStage.setTitle("Checkbox Demo"); primaryStage.setScene(scene); ; primaryStage.show/(); Public static void main(String[] args) { launch(args); TECHNICAL PUBLICATIONS® - an u-thniet far tanninay a nts Object Oriented Programming ia oe seeming \ and Components Output © Checkbox Demo Select your favorite color, [ } Red | Blue Green | Yellow ToggleButton + ToggleButton is a button control ti that has two States selected or deselected. # Toggle Group. From the same group at the. most only Af of that group remain descent Paton is selected rom that group then other buttons + Constructors + The ToggleButtons are placed in one button is selected at a time. 1. ToggleButton(): Creates a toggle button with an ‘empty string for its label. 2. ToggleButton(String txt): Creates a toggle button with the specified text as its label. * Methods 1. setToggleGroup(ToggleGroup val):Sets the value of the property toggleGroup. 2. setSelected(boolean val): Sets the value of the property selected, 3. isSelected(): Gets the value of the property selected. Example Program package application; import javafx.application. Application; import javafx.scene.Scene; import javafx.scene.layout. HBox; import javafx.geometry Insets; import javafx.scene.control._Label; : import javafx.scene.control.ToggleButton: import javafx.scene.control.ToggleGrouP: import javafx.stage.Stage; public class Main extends Application { one wold start(Stage primaryStage}throws Exception { public voi n =new HBox()i HBox root=new Ae root.setPadding(new Insets(15)); root.setSpacing(10)i | y atet( Lik"): id(ne' sildren().2d ~ root.getC! coma LIGATIONS® an uptusfr krowedge(Object Oriented Programming 29a ing, Controls and EVAPX Event Handling, Conrle and Ae Controls and Components "buon egg — "Uke 7 ove (Baa) RadioButtons ___ The Radio button control is used to make a choice. The difference between checkbox and radio button is that with checkbox we can have more than one selection but with radio button we select only one option at a time. | We can create a radiobutton as follows ~ RadioButton radioButton1 = new RadioButton("Label1"); We can group JavaFX RadioButton instances into a ToggleGroup. A ToggleGroup allows at most one RadioButton to be selected at any time. Following example shows how to create and use the radio button control. Programming Example package MyJavaFXApplication; import java.io.FileImputStream; import javafx.application. Application; | import static javafx application. Application launch; import javafx.event.ActionEvent; import javafx.event EventHandler; import javafx.scene.Scene; import javafx.scene.control. Label; import javafx.scene.control RadioButto import javafx scene.control-ToggleGrouP import javafx.scene. layout. VBox; import javafx.stage.Stages onjct rented Programming Text TextField control allows the qhe package javafy, control. user to enter the text th, at can be re Scene.control, Text; ‘an be read by the application. eld nee need to be imported for using the TextField Programming Example package MyJavaFXApplication: import java.io FileInputstream; import javafx.application. Application; import static javafx. application. Application launch; import javafx.event. ActionEvent; import javafx.event EventHandler; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control. TextField; import javafx.scene.layout.GridPane; import javafx.scene. layout. VBox; import javafx.stage Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage)throws Exception { Label L=new Label("Enter Name"); TextField tf=new TextField(); GridPane root=new GridPane(); root.addRow(0.L,tf); Scene scene = new Scene(root, 300, 200); "Text Field Demo"); primaryStage.setTitle(’ primaryStage.setScene(scene); primaryStage.show/(); t public static void main(String| launch(args); {] args) { — CAumGAL PUBLICATIONS® - an up-thnust for knowledgeobject Oriented Programming 5. root.addRow/(1,L2,t12) root.addRow(2.btn); Ds Scene scene = new Scene scone ~ new Scane(oot, 20, emacs setTitle("Toxt Field Dose age.setScens(aceny : primaryStage.show(), public static void mai mi Sa ‘in(String{] args) { } } 33 33__JavaFX Event Hanelir Sontrols and Components Output 1 Text Field Demo [Enter Name Parth Enter Password Submit TextArea control allows to enter multi The TextArea javatx.scene.control-TextArea ontrol can be created using new TextArea() Area using The textarea TextArea ta=: We can set the size of the Text. Following example shows how to © Programming Example package MyJavaFXApplication: import java.io. FileInputStreams import javat. ‘application. Application: ation. Application import static javatx.applicatio import javafx.event import javai-even™! Jine text. This control is represented by the class ePrefFleight( and setPrefWidth0 functions. sreate TextArea control jaunch; “ons® - an upahrust for knowiod?JavaFX Event Handling, Controls and Components Object Oriented Programming 5-4 import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.layout.GridPane; import javafx.stage.Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage)throws Exception { Label L=new Label("Enter your Comments: "); double width= 150; ta.setPrefHeight(height); ta.setPrefWidth(width); GridPane root=new GridPane(); : Toot.addRow/(0,L,ta); Scene scene = new Scene(root, 300, 200); primaryStage.setTitle("Text Area Demo"); primaryStage.setScene(scene); primaryStage.show/(); } public static void main(String|] args) { Jaunch(args); Output Product is excellent but it is costly. Enter your Comments: Improve packaging.object Oriented Programming ListView onents ymponents The JavaFX ListView control enabi able: ist of choices. S users hi choices. The 8 to choose one or m: JavaFX ListView jovab-tcchecontel.Liciviee wore options from a predefined control is ‘iad represented by the ¢ The ListView can be created by the class ListView listView. as follows ~ =new ListView() The items can be add is method. For example ided to i me ; to the ListView control usi jetewte sing getItems().add() method. For r listView.getltems().add(“Item 2"); To make a ListView vis ania isible we have to add it to the scene graph or to some la’ s then attached to the Scene object yyout component Followi ‘ing example program shows how to use ListView Control Programming Example package MyJavaFXApplication; import javafx.application Application; import static javafx.application.Application. launch; import javafx.event.ActionEvent; import javafx.event.EventHandk import javafx.scene.Scene; import javafx.scene. control.Label; import javafx.scene.control-ListView: import javafx,scene.controlSelectionMode; import javafx.scene.layout.GridPane; import javafx.stage.Stage; plication extends Application { public class MyJavaFXAP! @Override public void start(Stage primaryStage)throws Exception { rect your favorite programming Langusde Label L=new Label('Sel a is istView=new ListView); Ls Vow ty aloe stsencontestses TIPLE); st Views MUL tistview.getltems().add('Jave i istview.getitems()-2da c+ tistview.getitems()-24a PHP"); ListView getltems()-204 GridPane root=nes root.addRow (0.L lis View): “TIoNs® - an up-thrust for knowledge —5-36 JavaFX Event Handling, Controls and Components ramming Object Oriented Progr: Scene scene = new Scene(root, 350, me primaryStage.setTitle("ListView Demo’); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String|] args) { launch(args); } } cd Select your favorite program.. In above code we have used lstView getSelectionModel().setSelectionMode(SelectionMode. MULTIPLE), which allows multiple selection of items from listview. ComboBox We can have predefined list of choices using combo box. This control is represented by javatx.: itat the beginning of our application We can create the comboBox usit ComboBox cb: Scene.control. ComboBox class. Hence we n ‘eed to import program, ing following statement =new ComboBox(); Then we need to add the list of choices to the comboBox. This can be done usin, ch.getltems().add(Optiont") ch-getltems().add(‘Option2") And so on. —__ect Oriented Programming anh $37 ___savarx Event Handling, Controls and rollowing PFOgtam illustrates 2a 5 es the use of Combo iS program: programming Example package MyJavaFXApplication; port java.io.FileInputStream; import javafx.application. Application, import static javagx.a ic snpert jvatxevent-Actionzvont estan import javafx.event.EventHandler; import javafx.scene Scene; , import javafx.scene.control, ComboBox; import javafx.scene.controlLabel; import javafx.scene layout. GridPane; import javafx.stage Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage)throws Exception { Label L=new Label("Select your favorite programming Language: "); ComboBox ch=new ComboBox(); cb.getItems().add ("Java"); ch.getItems().add("C+ + ch.getItems().add("PHP" ch.getItems().add("Python’" GridPane root=new GridPane(); root.addRow(0,L,cb); Scene scene = new Scene(root, 360, 200); primaryStage.setTitle(‘ComboBox Demo’); primaryStage.setScene(scene); primaryStage.show(); } id main(Stri is) { public static void main(String|] ard: launch(args); t } Boy * control in the JavaFX application —— BriALICATIONS® - 8° UP rust for knowiedg@5-38 _ JavaFX Event Handling, Controls and Components Object Oriented Programming, Output = ComboBox Demo i Select your favorite programming Language: | Jave CH Isaa0l ChoiceBox The ChoiceBox control shows the set of items and allows user to select a single choice. It will show the currently selected item on the top. + By default the ChoiceBox control has no selected item. We have to specify the items from which the choice is to be made. + For using the ChoiceBox control we need to import javafx.scene.control.ChoiceBox package + Constructors of ChoiceBox Class are ChoiceBox(): It creates empty ChoiceBox ChoiceBox(ObservableList items): It creates empty ChoiceBox with the given set of items. Commonly Use Methods are Setlems(ObservableList value) | Itadds all the list items to ChoiceBox instance. setValue(T value) Sets the single choice value at a time, getltems() It gives the items of the ChoiceBox, getValue() {treads the ChoiceBox value means get the value show() Opens the list ofall choices from ChoiceBox. hide() Tt closes all the list of choices from ChoiceBox. TECHNICAL PUBLICATIONS® -an “p-tust for know a5-40__ JavaFX Event Handling, Controls and Components nted Programming, Object Oriented I Output ' ChoiceBox Demo My Favorite color is: | | Using the Scrollbar control the user can scroll down to the application page. For creating this control we use javafx.scene.control.ScrollBar class, Programming Example Package MyJavaFX Application; import javafx application. Applicatio import static javafx.application. Ap; import javatx.scene.Scene; import javafx.scene.control.Label; import javafx scene.control ScrollBar; ‘import javafx.scene lat yout.StackPane; *mport javaf.stage Stage; plication.launch; (Stage primarystage)throws Ex =new ScrollBar(); at StackPane root=new StackPane(); Toot.getChildren()add(sb); TECHNICAL PUBLICATIONS® -an YUst for knowledge PL—— me = Scene Scene = new Scene, £5 (00%, Java5X Been Ha primaryStage.setTitlo(‘Scrollbar Deyo ~ set Honing Controls and Components 0"); = primaryStage.setScene(scene) primaryStage.show(); : } public static void main(String! args) { launch(args); } t We can create the scrollbar in horizontal direction or in vertical direction. If we want the scrollbar to be displayed vertically then we call setOrientation() method sb.setOrientation (Orientation. VERTICAL); Similarly we can set minimum, maximum or current value to scrollbar using following functions (1) setMinQ) (2) setMax() (3) setValue() Following program makes use of these methods for the scrollbar control package MyJavaFXApplication; import javatx.application. Application; 7 import static javafs. application. Application launch; import javafx. geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control-Labeli .ScrollBar;5-42 __JavaFX Event Handling, Controls and Componenis Object Oriented Programming import javafx.stage Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage)throws Exception { ScrollBar sb=new ScrollBar(); sb.setMin(0); sb.setMax(50); sb.setValue(25); sb.setOrientation(Orientation. VERTICAL); StackPane root=new StackPane(); root. getChildren().add(sb); Scene scene = new Scene(root, 350, 200); primaryStage.setTitle("ScrollBar Demo"); primaryStage.setScene(scene); primaryStage.show(); t public static void main(String|] args) { launch(args); } } [53] Layouts + The arrangement of v 7 Be ‘arious components(nodes) in a scene withii " ayout of the container. ithin the container is called * For using the la i yout we must import the j : package javats. Th ed Pine i the base class for all the layouts in JavaFX. Bt Favabsscene-layout, The lass nam ‘arion . "ss layout panes are summarized in the following table. TECHNICAL PUBLICATIONS® - an up-thrus for knowledgec cect Oriented Programming obi 5-43 JavaFX Event Handling, Controls and Component { Layout Pane Descripti é - iption __ Box This layout pane arranges all the nodes in a single horizontal row. | __ vox ‘This layout pane arranges all the nodes in a single vertical column. StackPane i ‘ckPane | Inthis layout pane, the nodes are placed on top of each other in the center ofthe pane. GridPane _ | The nodes are placed in cell in two dimensional grid. FlowPane __ | Thisis a layout pane, in which the nodes are placed row by row horizontally or column by cohumn vertically. BordesPane | The nodes can be placed atthe top, bottom, left right or at he center regions. For adding the nodes to the layout manager follow the following step ~ (1) Instantiate the respective layout class. For example VBox root=new VBox(); (2) Then set the properties of the layout. ant the spacing between the created nodes then we use For example - if we w root.setSpacing(10); 3) Adding nodes to the layout object, for example - root getChildren().addAll( alignment ‘The overal alignment ofthe flowpane’s content within its width and height. ObjectProperty ‘columnHalignment | ™° Trorizontal alignment of nodes within each § column of a vertical flowpane- “The vertical alignment of nodes within each row sectProperty row Valignment ae of a horizontal flowpane- [praet “The amount of horizontal space Derwee" each gat Den a node in a horizontal flowpane oF the space between columns in a vertical flowpane- _— mA PUBLIGATONS® an spe or none ed: WaFX Event Handling, Controls and C Object Oriented Programming 5-44 _JavaPX Event Handling, Controls and Components DoubleProperty — vgap The amount of vertical space between each node in a vertical flowpane or the space between rows in a horizontal flowpane. Object?'ropertyOrientation> orientation _ | The orientation of this flowpane. * The FlowPane can be created using following syntax FlowPane flowpane = new FlowPane(); Programming Example package myjavafxapplication; import javafx.application. Application; import javafx.scene.Scene; import javafx.scene.control Button; import javafx.scene.layout. FlowPane; import javafx.stage.Stage; public class MyJavaFXApplication extends Application { @Override Public void start(Stage primaryStage) { FlowPane root=new FlowPane(); Button B1 = new Button("One'); Button B2 = new Button("Two'); Button B3 = new Button("Three'); Button B4 = new Button("Four’); Button BS = new Button('Five"); Button B6 = new Button('Six’); root.getChildren().add(B1); Toot.getChildren().add(B2); toot. getChildren().add(B3); toot. getChildren().add(B4), Toot.getChildren().add(B5), root. getChildren(),add(B6); Scene scene=, ‘new Scene(root, 150,150); PrimaryStage.setScene(scene); PrimaryStage.setTitle; ("FlowPane Demo"); PrimaryStage, show(); } Public static void m, ain(Strin, Jaunch(args); ll args) {4 object Oriented Programming. eo Ss FlowPane Demo Five | Six One | Two [ane | Two | Three | Four | Three | Four Five ce eal | Initially we get this window Ie expand the window horizontally, the buttons get arranged horizontally automatically [552] HBox ‘The HBox layout arranges the children in the form of horizontal rows. * The HBox class extends Pane class, Method getAlignment() getSpacing() Tt returns the value of alignment Property. Itretuims the spacing between its children, | Tt returns the spacing betwe setAlignment(Pos Value) getChildren() Itsets the alignment of the HBox. It returns the nodes in HBox. * The constructors of HBox class are - HBox(): Creates an HBox object with no nodes. HBox(double s): Creates an HBox with spacing in between nodes, Programming Example Package myjavatxapplication; import javafx.application. Application; import javafx.scene.Scene; import javafx.scene.control Button; import javatx.scene.layout. HBox; import javafx.stage Stage; Public class MyJavaFXApplication extends Application { TECHNICAL PUBLICATIONS® - an up-thrust for knowledge ' -ying a @Override public void start(Stage primarystage) { Box root=new HBOx(): Button B1 = new Button("One") Button B2 = new Button("TWo") Button B3 = new Button("Three’) Button B4 = new Button(Four’); Button BS = new Button('Five"): Scene scene=new Scene(root,200,100); cee root getChildren().addAl(B1,B2,B3.B4,B6): Ne ee al oN primaryStage.setScene(scene); primaryStage.setTitle("HBOX Demo’); [one | Two | Tee Four Five primaryStage.show(); — y public static void maint launch(args); + + Program Explanation : In above code, (1) We have created four button elements. (2) The layout pane is set as HBox. All the using getChildren(.addAll function. (3) This pane is then added to the Scene. .d this scene is then added to the PrimaryStage. (String{] args) { button elements are attached to the HBox pane by (4) Using setScene metho: vBox + The VBox layout arranges the children in the form of vertical rows. * The VBox class extends Pane class. «It requires javafx.scene-layout. VBox class which provides all the required methods of this pane. + Various methods used for layout using VBox are - Method Purpose getAlignment() It returns the value of alignment property. getSpacingd) Itzeturns the spacing between its children, setSpacing(value) It sets some spacing around the nodes of VBox setAlignment(Pos Value) _.| It sets the alignment of the VBox getChildren() It returns the nodes in VBox TECHNICAL PUBLIGATIONS® ~ an up-thust for knowledgeonents e by object Oriented Programming Ee «The constructors of VBox class a JavaFX Bvent Handling, Controls and Components S are - a corperen VBox(): Creates an VBox object with no nodes. (): Creat vi ject with no nod 101 VBox(double s): Creates an VBox with i signees spacing in between nodes. package myjavafxapplication; import javafx.application. Application; import javafx.scene.Scene; : import javafx.scene.control Button; import javafx.scene.layout.VBox; import javafx.stage Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage) { ‘VBox root=new VBox(); Button B1 = new Button("One"); Button B2 = new Button("Two'); Button B3 = new Button("Three’); Output Button B4 = new Button("Four’); Button B5 = new Button('Five’); Scene scene =new Scene(root, 100,150); root.getChildren(). addAll(B1,B2,B3,B4,B9); primaryStage.setScone(scene): primaryStage.setTitle("VBOX Demo"); primaryStage.show()i i public st Jaunch(args): } args) { atic void main(String! rust for knowied® sgarions® ono TECHNICAL PUBL!Object Oriented Programming. BorderPane 5-48 __ JavaFX Event Handlling, Controls and Components + BorderPane lays out children in top, left, right, bottom, and center positions. + Itcan be used to create the ‘ic looking application layouts. + It is represented by javafx.scene.layout.BorderPane class. + Various methods of BorderPane layout are | Method Description setBottom(node value) This method sets the bottom node of the border pane setCenter(node value) This method sets the center node of the border pane. setLeft(node value) ‘This method sets the left node of the border pane. setRight(node value) This method sets the right node of the border pane. setTop(node value) This method sets the top node of the border pane. © The BorderPane layout is created as follows ~ (2) BorderPane(): Creates a new Border Pane. (2) BorderPane(Node o): Creates a new Border Pane with specified node at center, (3) BorderPane(Node center, Node top, Node right, Node bottom, Node left): Creates an BorderPane layout wi the Border Pane, Programing Example Package myjavafxapplication; ‘ith the given Nodes to use for each of the main layout areas of import javafx.application. Application; import javafx.scene.Scene; import javafx.scene.control. Button; import javafx.scene layout. BorderPane; import javafx stage Stage; Public class Mi { @Override Public void start { Button B top = new Button B center Button B bottom 'yJavaFXApplication extends Application (Stage primaryStage) Button('One'); new Button("Two'); = new Button("Three"); TECHNICAL PUBLICATIONS® an p-thnust for knowiecdg5-49 _JavaEX Event Handling, Contro's 2° “Sn — Object Oriented Programming Button B_left = new Button(‘Four’}; a Output BorderPaneD.. = — Button B_right = new Button(‘Five"); x BorderPane root = new BorderPane(); Toot.setTop(B_top); root.setCenter(B_center); Toot.setBottom(B_bottom); root.setLeft(B_left); root.setRight(B right); Scene scene=new Scene(root,250,250); primaryStage.setScene(scene); primaryStage.setTitle("BorderPane Demo"); primaryStage.show(); } Public static void main(String|] args) { launch(args); } } StackPane * StackPane is a layout in which every new node is placed on the top of previous node. + It makes use of javafx.scene layout.StackPane class. + Various methods of StackPane layout are - Method Purpose getAlignment() Retums the alignment of the StackPane. .getAlignment(Node c) Returns the node's alignment getMargin(Node o) Retums the insets of the node setAlignment(Node n, Pos v) _| Sets the alignment of the node which is a part of StackPane setAlignment(Pos v) Sets the alignment of the StackPane setMargin(Noden, Insets v)_| Sets the margin of the node which is a part of StackPane. © The constructor for StackPane layout is 1. StackPane() 2. StackPane(Node... Children) Programming Example Package myjavafxapplication; TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeObject Oriented Programming 5-50 _ JavaFX Event Handling, Controls and Components import javatx application. Application; import javatx.scene.Scene; import javafx.scene.control. Button; import javafx.scene layout, StackPane; import javafx.stage.Stage; Public class MyJavaFXApplication extends Application { @Override Public void start(Stage primaryStage) { StackPane root=new StackPane(); Button B1 = new Button("This button is with caption One"); Button B2 = new Button("Two is on its top" Button B3 = new Button("Thres"); Scene scene=new Scene(root,100,150); Output Toot.getChildren().addAll(B1,B2,B3); primaryStage.setScene(scene); primaryStage.setTitle("StackPane Demo primaryStage.show(); + Public static void main(String|] args) { launch(args); } GridPane places its nodes into a grid of rows and col columns. GridPane is the most flexible built lumns. Nodes may span multiple rows or in layout pane. The GridPane is given by Buttont | Button2 Button3 | Button Button | Buttons Mies) Buttons | TEGHNICAL PUBLICATIONS® an uptiust for knowodge Fol pa BE puor oriented Programming jus methods used in GridPane are - — “oid add(Node child, int columnindes, int ex) rowlnd! void add(Node child, int columnindes, int Index, int colspan, int rowspan) yoid addColumn(int columnlndex, Node. hildren) JavaFX Event Hanal ling, Controls and Componey Components Danae ~ Adds a child to the gridpane at the specified ccolumn,row position and spans, ‘This method is for placing the specified nodes sequentially in a given column of the gridpane, oid addRow(int rowIndex, Node... children) ‘This method is for placing the specified nodes sequentially in a given row of the gridpane. ObjectProperty alignmentProperty() ‘The alignment of of the grid within the gridpane's width and height. Pos getAlignment() Gets the value of the property alignment. void setHgap(double value) Sets the value of the property hgap. void setVgap(double value) The constructor used for GridPane layout is Sets the value of the property vgap GridPane gridPane = new GridPane(); Following example shows the use of GridPane layout Programming Example package myjavafxapplication; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene layout.GridPane; import javafx.stage.Stage; public class MyJavaFXApplication extends Application { @Override public void start(Stage primaryStage) { GridPane grid=new GridPane(); Button B1 = new Button("One’): Button B2 = new Button("Two'}; Button B3 = new Button(‘Thres!); Button B4 = new Button("Four’); Button BS = new Button(‘Five’); Button B6 = new Button(‘Six’); TECHNICAL PUBLICA’ TIONS? - apenas ese ‘an upthrust for knowledgeObject Oriented Programming. JavaFX Event Handling, Controls and Components grid.add(B1,0,0); grid.ada(B2,1,0); grid.add(B3,2,0); grid. ada(B4,0,1); gtid.add(BS, 1,1); Output grid.ada(B6,2,1); ‘Scene scene=new Scene(grid, 150,150); oe { One | Two | Three primaryStage.setScene(scene); primaryStage.setTitle("GridPane Deino"); T Four | Five | Six primaryStage.show(); } public static void main(String|] args) { launch(args); } + Menus [zi] menu + In JavaFX we can create a menu using a Menu class. = For using the Menu class in our JavaFX application we need to import javafx.scene.control. Menu so that the methods associated with this class can be used in the application. * Menu is a popup menu that contains several menu items that are displayed when the user clicks a menu. The user can select a menu item from the menu. © Constructors for Menu class are Menu() |[€reates an empty menu Menu(String str) Creates a menu with string str as label. Menu(String str,Node nd) Creates a menu with string str as label and nd as graphics node. Menu(String stz, Node nd,ltem...i) _ | Creates a menu with string str as label, nd as graphics node and add given item to the list TECHNICAL PUBLICATIONS® - an up-thrust for knowledgeObject Oriented Programming + Commonly used Methods are items of the hide the menu The menus to show within this Menabar + Constructors for MenuBar class are MenuBar() Creates a new empty Menubar MenuBar(Menu... m) Menultem + A Menultem is a basic item that goes on a menu. Creates a new menubar with given set of menus * Following Fig. 5.6.1 shows the menu, menubar and menuitems. 71 JavaFX Menu Demo. Open File | Menu Save | Exit oe Menu items Fig. 5.6.1 Representing amenu —Feimat At PLBLEATIONS?- upto a IST SiNObject Oriented Programming 5-54 ___ JavaFX Event Handling, Controls and Components Steps for creating JavaFX application for creating Menu Step 1: Create a Menu bar is the first step, MenuBar can be instantiated using new MenuBar menuBar = new MenuBar(); Step 2: Now create the menu. The name of the menu is passed as an argument to the Menu clas Menu fileMenu = new Menu('File"); Create the menuitem. The name of the menu is passed as an argument to the Step 3 Menultem class. Menultem newltem = new Menultem("New'); Step 4: Add menu items to the menu using add or addAlll method fileMenu.getItems().addAll(newltem, openFileltem,saveltem, exitItem); Step 5: Add Menu to Menu Bar using add or addAll method. menuBar.getMenus().addAll(fileMenu, editMenu, aboutMenu); Programming Example package application; import javatx.application. Application; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control. MenuBar; import javafx.scene.control. Menultem; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage stage) { // Creating MenuBar MenuBar menuBar = new MenuBar(); // Creating three menus Menu fileMenu = new Menu('File"); Menu editMenu = new Menu("Edit"); Menu aboutMenu = new Menu("About"); // Creating Menultems for File menu Menultem newltem = new Menultem("New"); ‘Menultem openFileltem = new Menultem("Open File’ Menultem saveltem = new Menultem('Save"); Menultem exititem = new Menultem('Exit"); TECHNICAL PUBLICATIONS® . an up-thrust for knowledge