Feeds:
Posts
Comments

After a long time, i took some time to write the blog. This is my first blog on JavaFX 2.2.Got inspired after seeing some text field with close button like spotlight in mac and other applications.

The code in this blog can be improved using css.

TextField realized on the stage.


Image showing the close button in the text field after typing some characters.


Selected content of the textfield.

Functionality of the this textfield

  •  Show the textfield with close button when characters are typed.
  • Remove the content of the textfield when the close button is clicked & close button gets disappear.
  • Remove the content of the textfield when user selects the characters or delete the character by character , the close button gets disappear.
FileName : CustomTextField.java

package customtextfieldjavafx;

import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;

/**
 *
 * @author Lawrence PremKumar
 */
public class CustomTextField extends Group {

    TextField tc = null;
    Group closeButton = null;

    public CustomTextField() {
        tc = new TextField();
        tc.setStyle(".text-field,.text-field-focused");
        tc.setOnKeyTyped(new EventHandler() {
            @Override
            public void handle(KeyEvent event) {

                System.out.println(tc.getText().length());
                if ((tc.textProperty().get().length() < 0) || (tc.textProperty().get().equals(""))) {                     closeButton.setVisible(false);                 } else if (tc.textProperty().get().length() > -1) {
                    closeButton.setVisible(true);
                }
            }
        });

        closeButton = getCloseButton();
        closeButton.setOnMouseClicked(new EventHandler() {
            @Override
            public void handle(MouseEvent t) {
                closeButton.setVisible(false);
                tc.clear();
            }
        });

        GridPane grid = new GridPane();
        grid.setLayoutX(1.0);
        grid.setLayoutY(1.0);
        grid.setHgap(0.0);
        ColumnConstraints txtComponent = new ColumnConstraints();
        txtComponent.setHalignment(HPos.RIGHT);
        grid.getColumnConstraints().add(txtComponent);
        ColumnConstraints closeBtn = new ColumnConstraints();
        closeBtn.setHalignment(HPos.LEFT);
        grid.getColumnConstraints().add(closeBtn);
        grid.add(tc, 0, 0);
        grid.add(closeButton, 1, 0);

        Rectangle focusBorder = new Rectangle();
        focusBorder.setFill(null);
        focusBorder.setStrokeWidth(2.0);
        focusBorder.setStroke(Color.web("#097dda"));
        focusBorder.widthProperty().bind(grid.widthProperty().add(2));
        focusBorder.heightProperty().bind(grid.heightProperty().add(2));
        focusBorder.visibleProperty().bind(tc.focusedProperty());

        this.getChildren().addAll(focusBorder, grid);
    }

    private Group getCloseButton() {
        Group grp = new Group();
        final Circle circle = new Circle();
        circle.setRadius(7.0);
        final Rectangle r1 = getCard();
        r1.setRotate(-45);
        final Rectangle r2 = getCard();
        r2.setRotate(45);
        grp.setOnMouseEntered(new EventHandler() {
            @Override
            public void handle(MouseEvent t) {
                circle.setFill(Color.web("#097dda"));
                r1.setFill(Color.WHITE);
                r2.setFill(Color.WHITE);
            }
        });
        grp.setOnMouseExited(new EventHandler() {
            @Override
            public void handle(MouseEvent t) {
                circle.setFill(Color.web("#4c4c4c"));
                r1.setFill(Color.web("#868686"));
                r2.setFill(Color.web("#868686"));
            }
        });
        grp.setVisible(false);
        circle.setFill(Color.web("#4c4c4c"));
        grp.getChildren().addAll(circle, r1, r2);
        return grp;
    }

    private Rectangle getCard() {
        Rectangle card = RectangleBuilder.create()
                .x(-4)
                .y(-1)
                .width(8)
                .height(2)
                .strokeWidth(1.0)
                .fill(Color.web("#868686"))
                .build();
        return card;
    }
}

Usage of the Custom TextField
FileName : CustomTextFieldJavaFX.java

package customtextfieldjavafx;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author Lawrence PremKumar
 */
public class CustomTextFieldJavaFX extends Application {

    @Override
    public void start(Stage primaryStage) {

        CustomTextField custTextField = new CustomTextField();
        custTextField.setLayoutX(10.0);
        custTextField.setLayoutY(10.0);

        Scene scene = new Scene(custTextField, 300, 250);
        scene.getStylesheets().add(CustomTextField.class.getResource("mycss.css").toExternalForm());
        primaryStage.setTitle("CustomTextFieldJavaFX..!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

CSS file

/*
Document   : mycss
Created on : Sep 15, 2012, 4:18:16 PM
Author     : lawkp
Description:
Purpose of the stylesheet follows.
*/

.text-field:focused {
-fx-background-color: null;
-fx-background-insets: 0, 1, 2;
-fx-background-radius: 1;
}

.text-field{
-fx-border-color: null;
-fx-border-radius: 0;
-fx-select-on-focus:false;
}

Few months before, just tried my own implementation of popup, where i used windows. Now i have used Popup Control. And also

i have showed how to implement a simple popup menuitem & how to show the popup. May be useful for some one else.

File Name : TestPopupMenu.java

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Popup;
import javafx.stage.Stage;

/**
 *
 * @author lawrence premkumar
 */
public class TestPopupMenu extends Application {

    @Override
    public void start(Stage stage) throws Exception {

        Group root = new Group();
        Scene scene = new Scene(root, 800, 600, Color.AQUA);
        final VBox layout = new VBox();
        layout.getChildren().addAll(new PopupMenuItem("Lawrence").getPopupMenuItem(), new PopupMenuItem("PremKumar").getPopupMenuItem());
        Text t = new Text("Right click on the Rectangle to \n Invoke the Popup.");
        t.setFont(new Font(25));
        t.setLayoutX(20.0);
        t.setLayoutY(20.0);
        final Rectangle r = new Rectangle(200, 200);
        r.setLayoutX(100.0);
        r.setLayoutY(70.0);
        r.setFill(Color.ORANGE);
        r.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent e) {

                if (e.getButton() == javafx.scene.input.MouseButton.SECONDARY) {
                    Popup popup = new Popup();
                    popup.getContent().add(layout);
                    popup.show(r, e.getScreenX(), e.getScreenY());
                }
            }
        });
        root.getChildren().addAll(t,r);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String args[]) {
        Application.launch(TestPopupMenu.class, args);
    }
}

File Name : PopupMenuItem.java

import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

/**
 *
 * @author lawrence premkumar
 */
public class PopupMenuItem  {

    Label lbl;
    Rectangle menuItemBGRectangle;

    PopupMenuItem(String name, ImageView imgView) {
        this.lbl = new Label(name , imgView);
    }

    PopupMenuItem(String name) {
        lbl = new Label(name);
    }

    public Group getPopupMenuItem(){
        Group grp = new Group();

        lbl.setLayoutX(10.0);
        menuItemBGRectangle = new Rectangle();
        menuItemBGRectangle.setWidth(200.0);
        menuItemBGRectangle.setHeight(20.0);
        menuItemBGRectangle.setFill(Color.web("#f6f6f6"));
        menuItemBGRectangle.setOnMouseEntered(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent e) {
                menuItemBGRectangle.setFill(Color.BLUE);
                lbl.setTextFill(Color.WHITE);
            }
        });

        menuItemBGRectangle.setOnMouseExited(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent e) {
                menuItemBGRectangle.setFill(Color.web("#f6f6f6"));
                lbl.setTextFill(Color.BLACK);
            }
        });

        grp.getChildren().addAll(menuItemBGRectangle, lbl);
        return grp;
    }

We all know that Stack is an abstract data type and data structure in any programming language.  Stack works as Last in First out (LIFO).  This blog is to show the functionality of the stack visually, how to show multiple stage and how to insert the node into the layout by specifying the index, get the size of the layout ( number of elements in the layout) and finally delete the node from the layout.

I have used VBox layout for showing the element vertically.

File Name : StackElement.java


import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;

/**
 *
 * @author Lawrence PremKumar
 */
public class StackElement {

    public String value;
    private Label txt;

    StackElement() {
    }

    StackElement(String val) {
        txt = new Label(val);
        txt.setFont(new Font(15));
        txt.setLayoutX(10.0);
    }

    public Group getElement() {
        Group grp = new Group();
        Rectangle rect = new Rectangle(150, 30);
        rect.setFill(Color.RED);
        grp.getChildren().addAll(rect, txt);
        return grp;
    }
}

 

File Name : StackUI.java

import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
*
* @author Lawrence PremKumar
*/
public class StackUI extends Application {

     VBox layout = new VBox();

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

     @Override
     public void start(Stage stage) throws Exception {
          Group root = new Group();
          Scene scene = new Scene(root, 200, 400);
          stage.setScene(scene);
          stage.setTitle("Visual Stack UI");
          layout.setSpacing(2.0);
          root.getChildren().addAll(layout);
          stackControl();
          stage.setVisible(true);
    }

     public void stackControl() {
         Stage stg = new Stage();
         stg.setX(10.0);
         stg.setY(10.0);
         Group root = new Group();
         Scene scene = new Scene(root, 400, 50);
         stg.setScene(scene);

         Label lbl1 = new Label("Enter the data : ");
         final TextBox tb = new TextBox(30);
         Button pushBtn = new Button("Push");

         pushBtn.setOnAction(new EventHandler<ActionEvent>() {
              @Override
              public void handle(ActionEvent e) {
                   StackElement stkElement = new StackElement(tb.getText());
                   Group grp = stkElement.getElement();
                   layout.getChildren().add(0, grp);
                   FadeTransition ft = new FadeTransition(Duration.valueOf(1000), grp);
                   ft.setFromValue(0.1);
                   ft.setToValue(1.0);
                   ft.play();
                   tb.setText("");
             }
         });
         Button popBtn = new Button("Pop");
         popBtn.setOnAction(new EventHandler<ActionEvent>() {

              @Override
              public void handle(ActionEvent e) {
                   if(!layout.getChildren().isEmpty()) {
                      layout.getChildren().remove(0);
                  }
             }
         });

         HBox layout1 = new HBox();
         layout1.setSpacing(5.0);
         layout1.setLayoutX(10.0);
         layout1.getChildren().addAll(lbl1, tb, pushBtn, popBtn);
         root.getChildren().add(layout1);
        stg.setVisible(true);
   }
}

If you have a bigger image and it has to be loaded into your application, then it can be loaded in background. While the bigger is getting loaded, we can show a thumb nail or we can show a place holder image. Once the bigger image gets loaded into your memory, it can be shown into your application. The percentage of the image which is getting loaded can be tracked. This is shown in the following sample.

InitialImage

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author Lawrence PremKumar
 */
public class ImgBackgroundLoading extends Application {

    public static void main(String[] args) {
        Application.launch(ImgBackgroundLoading.class, args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 600, 600);

        Rectangle bg  = new Rectangle();
        bg.setWidth(600.0);
        bg.setHeight(600.0);

        final Text progressText = new Text("0 %");
        progressText.setFont(new Font(100));
        progressText.setFill(Color.BLUEVIOLET);

        final ImageView imgView = new ImageView();
        final Image img = new Image("http://www.webmastergrade.com/wp-content/uploads/2009/12/Christmas-Snow-Man.jpg" ,true);
        img.progressProperty().addListener(new ChangeListener<Number>() {
                public void changed(ObservableValue ov,
                    Number old_val, Number new_val) {
                    progressText.setContent((int)new_val.doubleValue() +" %");
                    if(new_val.doubleValue() == 100.0){
                        imgView.setFitHeight(600.0);
                        imgView.setFitWidth(600.0);
                        imgView.setImage(img);
                    }
                }
            });

        final Image tempImg = new Image(ProgressBarExample.class.getResourceAsStream("bird1.jpg"));
        VBox layout = new VBox();
        imgView.setImage(tempImg);
        layout.getChildren().addAll(progressText,imgView);
        root.getChildren().addAll(bg,layout);
        primaryStage.setScene(scene);
        primaryStage.setVisible(true);
    }
}

lastimg


Popup is special window(no decorations with a null fill), like container for a scene graph which is seen above the stage and its invoked when user right clicks on the Node. This blog is an initial draft for the special popup i,e this SpecialPopup is different from the usual popup. SpecialPopup can be created like matrix. This SpecialPopup is created using TilePane for laying out the individual PopupMenuItem. I will develop this initial draft of this control as a full fluged control going forward.
Note : Image used for this example

SpecialPopup image is missingFilename : PopupMenuItem.java

package popup;

import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

/**
 *
 * @author Lawrence PremKumar
 */
public class PopupMenuItem extends Group{

    public Label popUpMenuItem  ;
    final Rectangle bgRect = new Rectangle();

    PopupMenuItem(){
        popUpMenuItem = new Label();
    }
    PopupMenuItem(String menuName ,  javafx.scene.control.ContentDisplay labelPos ,ImageView imgView){
        popUpMenuItem = new Label(menuName,imgView);
        popUpMenuItem.setContentDisplay(labelPos);
        popUpMenuItem.setTextFill(Color.WHITE);
    }

    public Group createPopupMenuItem(){

        this.setOnMouseEntered(new EventHandler() {
            public void handle(MouseEvent event) {
                 bgRect.setWidth(popUpMenuItem.getWidth()+2);
                 bgRect.setHeight(popUpMenuItem.getHeight()+2);
                 bgRect.setArcHeight(5.0);
                 bgRect.setArcWidth(5.0);
                 bgRect.setFill(Color.BLACK);
                 bgRect.setOpacity(0.5);
            }
        });

        this.setOnMouseExited(new EventHandler() {
            public void handle(MouseEvent event) {
                  bgRect.setOpacity(0.0);
                  System.out.println("Mouse exited \n");
            }
        });

        this.getChildren().addAll(popUpMenuItem,bgRect);
        return this;
    }
}

Filename : PopupMenu.java

 
package popup; 
import javafx.geometry.Orientation; 
import javafx.scene.layout.TilePane; 
 
 /*
  * @author Lawrence PremKumar 
  *
 */ 
  final public class PopupMenu extends TilePane {
    PopupMenu() {
    }
    PopupMenu(double hgap, double vgap) {
        super(hgap, vgap);
    }

    public boolean add(java.util.ArrayList popupArray) {
        boolean flag = true;
        for (int i = 0; i <= popupArray.size();i++) { 
	flag = this.getChildren().add(popupArray.get(i).createPopupMenuItem());
            if (!flag) {
                break;
            } else {
                continue;
            }
        }
        return flag;
    }
}

Filename : TestPopup.java

package popup; 
import javafx.application.Application; 
import javafx.event.EventHandler; 
import javafx.geometry.Orientation; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.control.ContentDisplay; 
import javafx.scene.effect.DropShadow; 
import javafx.scene.image.Image; 
import javafx.scene.image.ImageView; 
import javafx.scene.input.MouseButton; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color; 
import javafx.scene.paint.CycleMethod; 
import javafx.scene.paint.LinearGradient; 
import javafx.scene.paint.Stop; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 
import javafx.stage.StageStyle; 

/** 
 * 
 * @author Lawrence PremKumar 
 */

public class TestPopup extends Application {

    Stage stage1 = null;
    PopupMenuItem1 menu1 = null;
    PopupMenuItem1 menu2 = null;
    PopupMenuItem1 menu3 = null;
    PopupMenuItem1 menu4 = null;

    public static void main(String[] args) {
        Application.launch(TestPopup.class, args);
    }

    @Override
    public void start(final Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        Group root = new Group();
        Scene scene = new Scene(root, 300, 250);
        ImageView imgView = new ImageView();
        imgView.setFitHeight(40.0);
        imgView.setFitWidth(40.0);
        Image img = new Image(TestPopupControl.class.getResourceAsStream("duke.jpg"));
        imgView.setImage(img);
        Image img1 = new Image(TestPopupControl.class.getResourceAsStream("duke.jpg"));
        ImageView imgView1 = new ImageView();
        imgView1.setFitHeight(40.0);
        imgView1.setFitWidth(40.0);
        imgView1.setImage(img1);
        Image img2 = new Image(TestPopupControl.class.getResourceAsStream("duke.jpg"));
        ImageView imgView2 = new ImageView();
        imgView2.setFitHeight(40.0);
        imgView2.setFitWidth(40.0);
        imgView2.setImage(img2);
        menu1 = new PopupMenuItem1("One", ContentDisplay.TOP, imgView);
        menu2 = new PopupMenuItem1("Two", ContentDisplay.TOP, imgView1);
        menu3 = new PopupMenuItem1("Three", ContentDisplay.TOP, imgView2);
        menu1.setOnMouseClicked(new MouseEventHandler());
        menu2.setOnMouseClicked(new MouseEventHandler());
        menu3.setOnMouseClicked(new MouseEventHandler());
        final java.util.ArrayList popupArray = new java.util.ArrayList();
        popupArray.add(menu1);
        popupArray.add(menu2);
        popupArray.add(menu3);
        Rectangle bgRect = new Rectangle();
        bgRect.setWidth(200);
        bgRect.setHeight(130);
        bgRect.setArcHeight(5.0);
        bgRect.setArcWidth(5.0);
        bgRect.setFill(Color.RED);
        final PopupMenu popup = new PopupMenu(5, 5);
        popup.setHgap(5.0);
        popup.setLayoutX(5.0);
        popup.setLayoutY(7.0);
        popup.setPrefColumns(3);
        popup.setPrefRows(1);
        popup.add(popupArray);
        bgRect.setOnMouseClicked(new EventHandler() {
            public void handle(MouseEvent event) {
                if (event.getButton() == MouseButton.SECONDARY) {
                    stage1 = new Stage(StageStyle.TRANSPARENT);
                    Group rootGroup = new Group();
                    DropShadow ds = new DropShadow();
                    rootGroup.setEffect(ds);
                    ds.setOffsetY(3.0f);
                    ds.setColor(Color.color(0.4f, 0.4f, 0.4f));
                    Scene scene = new Scene(rootGroup);
                    scene.setFill(null);
                    Rectangle r = new Rectangle();
                    r.setWidth(140);
                    r.setHeight(70);
                    Stop[] stops = new Stop[]{new Stop(0, Color.web("#1F6592")), new Stop(1, Color.web("#80CAFA"))};
                    LinearGradient lg = new LinearGradient(125.0, 0.0, 225.0, 0.0, true, CycleMethod.NO_CYCLE, stops);
                    r.setFill(lg);
                    r.setArcHeight(10.0);
                    r.setArcWidth(10.0);
                    rootGroup.getChildren().addAll(r, popup);
                    stage1.setScene(scene);
                    stage1.setX(event.getScreenX());
                    stage1.setY(event.getScreenY());
                    stage1.setVisible(true);
                }
            }
        });
        root.getChildren().addAll(bgRect);
        primaryStage.setScene(scene);
        primaryStage.setVisible(true);
    }

    public class MouseEventHandler implements EventHandler {
        public void handle(MouseEvent me) {
            if (me.getSource().equals(menu1)) { 
                // Action specific to menu1 
                stage1.close(); 
            } 
            if(me.getSource().equals(menu2)){ 
                // Action specific to menu2 
                stage1.close(); 
            } 
            if(me.getSource().equals(menu3)){ 
                // Action specific to menu3 
                stage1.close(); 
            } 
        } 
    } 
}

Tried creating a simple “Current Date Widget” using JavaFX 2.0.

Datewidget image file not available

While trying to develop current Date widget came to know that right now its not possible to create a main stage as undecorated. This is because, JavaFX 2.0 dn’t have stage.setStyle() method. But other than the primary stage or main Stage, all other stages can be created as undecorated or decorated depending upon the users choice.

First let me show you how to close the primary stage without user interaction.Add a button to the stage and call the button.fire(); this method arms the button & triggers the ActionEvent.
Note:- According to the doc on fire(), “This function is intended to be used by experts, primarily by those implementing new Skins or Behaviors. It is not common for developers or designers to access this function directly.”

Stage is closed using stage.close() method.
Stage(StageStyle.UNDECORATED) is used to create a undecorated stage.

“To make it more dynamic, i need to implement a timer class and update the date very 5 minutes or to some nth min.”


import java.util.Calendar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Light.Distant;
import javafx.scene.effect.Lighting;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
*
* @author Lawrence PremKumar
*/

public class TodaysDateWiget extends Application {

	final double WIDTH = 150.0;
	final double HEIGHT = 150.0;

	public static void main(String[] args) {
		Application.launch(TodaysDateWiget.class, args);
	}

	@Override
	public void start(Stage primaryStage) {
		primaryStage.setTitle("Hello World");
		Group root = new Group();
		Scene scene = new Scene(root, 300, 250, Color.LIGHTGREEN);
		Button btn = new Button();
		btn.setLayoutX(100);
		btn.setLayoutY(80);
		btn.setText("Hello World");
		btn.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
			public void handle(ActionEvent event) {
				Stage st = new Stage(StageStyle.UNDECORATED);
				Group group = new Group();
				Scene s = new Scene(group ,WIDTH+3,HEIGHT+5);
				s.setFill(null);
				group.getChildren().addAll(getToDayControl());
				st.setScene(s);
				st.setVisible(true);

			}
		});
		btn.fire();
		root.getChildren().add(btn);
		primaryStage.setScene(scene);
		primaryStage.setVisible(false);
		primaryStage.close();
	}

	public Group getToDayControl(){
		String[] months = {"Jan", "Feb","Mar", "Apr", "May",          "Jun", "Jul","Aug", "Sep", "Oct", "Nov","Dec"};
		Calendar cal =  Calendar.getInstance();

		Group ctrl = new Group();
		Rectangle rect = new Rectangle();
		rect.setWidth(WIDTH);
		rect.setHeight(HEIGHT);
		rect.setArcHeight(10.0);
		rect.setArcWidth(10.0);

		Rectangle headerRect = new Rectangle();
		headerRect.setWidth(WIDTH);
		headerRect.setHeight(30);
		headerRect.setArcHeight(10.0);
		headerRect.setArcWidth(10.0);

		Stop[] stops = new Stop[] { new Stop(0, Color.color(0.31, 0.31, 0.31, 0.443)), new Stop(1,  Color.color(0, 0, 0, 0.737))};
		LinearGradient lg = new LinearGradient( 0.482, -0.017, 0.518, 1.017, true, CycleMethod.REFLECT, stops);
		headerRect.setFill(lg);

		Rectangle footerRect = new Rectangle();
		footerRect.setY(headerRect.getBoundsInLocal().getHeight() -4);
		footerRect.setWidth(WIDTH);
		footerRect.setHeight(125);
		footerRect.setFill(Color.color(0.51,  0.671,  0.992));

		final Text currentMon = new Text(months[(cal.get(Calendar.MONTH) )]);
		currentMon.setFont(Font.font("null", FontWeight.BOLD, 24));
		currentMon.setTranslateX((footerRect.getBoundsInLocal().getWidth() - currentMon.getBoundsInLocal().getWidth())/2.0);
		currentMon.setTranslateY(23);
		currentMon.setFill(Color.WHITE);

		final Text currentDate = new          Text(Integer.toString(cal.get(Calendar.DATE)));
		currentDate.setFont(new Font(100.0));
		currentDate.setTranslateX((footerRect.getBoundsInLocal().getWidth() - currentDate.getBoundsInLocal().getWidth())/2.0);
		currentDate.setTranslateY(120);
		currentDate.setFill(Color.WHITE);

		ctrl.getChildren().addAll(rect, headerRect, footerRect , currentMon,currentDate);

		DropShadow ds = new DropShadow();
		ds.setOffsetY(3.0);
		ds.setOffsetX(3.0);
		ds.setColor(Color.GRAY);
		ctrl.setEffect(ds);

		return ctrl;
	}
}

TabPane is one of the most commonly used component in any client side application. This blog shows you how to create a TabPane in JavaFX 2.0 and how to change its side dynamically apart from this it even shows you how to create and use the RadioButton.

 

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Side;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
*
* @author Lawrence PremKumar
*/
public class TabPaneExample extends Application {
	TabPane tabPane = null;
	ChoiceBox cb = new ChoiceBox();
	Color colors[] = {Color.BLUE, Color.RED, Color.GREEN, Color.GOLD};

	@Override
	public void start(Stage stage) throws Exception {
		stage.setTitle("Tab Example");
		Group root = new Group();
		Scene scene = new Scene(root, 500, 500);</p>

	     	// create a TabPane instance
		tabPane = new TabPane();
		tabPane.setLayoutX(20);
		tabPane.setLayoutY(20);

		// create individual tabs
		for (int i = 0; i &lt; colors.length; i++) {
			Tab tab = new Tab();
			// set the label for tab
			tab.setText("Tab # " + (i + 1));

			// add the content to tab
			tab.setContent(new Rectangle(400, 400, colors[i]));

			// add the tab to TabPane
			tabPane.getTabs().add(tab);
		}

		//create a hbox to hold the radio buttons
		HBox sideLayout = new HBox();
		sideLayout.setSpacing(10);

		final ToggleGroup tg = new ToggleGroup();
		RadioButton top = new RadioButton("Top");
		top.setSelected(true);
		top.setUserData("Top");
		top.setToggleGroup(tg);

		RadioButton bottom = new RadioButton("Bottom");
		bottom.setToggleGroup(tg);
		bottom.setUserData("Bottom");

		RadioButton left = new RadioButton("Left");
		left.setToggleGroup(tg);
		left.setUserData("Left");

		RadioButton right = new RadioButton("Right");
		right.setToggleGroup(tg);
		right.setUserData("Right");

		sideLayout.getChildren().addAll(top, bottom, left, right);

		// Add change listener to toggleGroup
		tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {

			public void changed(ObservableValue< extends Toggle> observable,
					Toggle oldValue, Toggle newValue) {
				String selectedValue = tg.getSelectedToggle().getUserData().toString();
				System.out.println(selectedValue);
				if (selectedValue.equals("Top")) {
					tabPane.setSide(Side.TOP);
				}
				if (selectedValue.equals("Bottom")) {
					tabPane.setSide(Side.BOTTOM);
				}
				if (selectedValue.equals("Left")) {
					tabPane.setSide(Side.LEFT);
				}
				if (selectedValue.equals("Right")) {
					tabPane.setSide(Side.RIGHT);
				}
			}
		});

		root.getChildren().addAll(sideLayout, tabPane);
		stage.setScene(scene);
		stage.setVisible(true);
	}

	public static void main(String[] args) {
		Application.launch(TabPaneExample.class, args);
	}
}

Follow

Get every new post delivered to your Inbox.