Friday, 10 July 2015

Filled Under:

Tutorial On Combo Box In JavaFX

Previously I have covered tutorial on JCombo box in swing this tutorial is also about combo box but its different from previous one in this program I have tried to  demonstrate how to create combo box by using JavaFx library and how to select its items using javaFx events.

METHODS USED IN THIS PROGRAM:

In this program I have add items in combo box using getItems().addAll you can also use ObservableList to add items in combo box.

setLayoutX(Double) And setLayoutY(Double)

These methods is used set the layout of component in javaFx first method is used to define the x-cordinate of component while second component defines the y-cordinate of component.

setFill(Paint Value):

This method is used to fill the background paint of scene or component.Its default colour is white.

CODING:

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.ComboBox;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.paint.Color;


public class mainfx extends Application {

ComboBox mycombo = new ComboBox();
Rectangle r = new Rectangle(0,0,2000,2000);
Button btn = new Button("Click To Change Colour");

@Override
public void start(Stage primaryStage) {

Group root = new Group();      
Scene scene = new Scene(root, 300, 250); 
mycombo.setPromptText(" SELECT  COLOUR ");
mycombo.getItems().addAll("LIGHTCYAN","DIMGREY","GOLD","AQUA");
mycombo.setLayoutX(150);
mycombo.setLayoutY(90);
mycombo.setMinSize(150, 50);
btn.setLayoutX(340);
btn.setLayoutY(105);
r.setFill(Color.WHITE);
primaryStage.setTitle("FX ComboBox");
root.getChildren().add(r);
root.getChildren().add(mycombo);
root.getChildren().add(btn);
primaryStage.setScene(scene); 
primaryStage.show();

btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {

int a = mycombo.getSelectionModel().getSelectedIndex();

if(a==0)
{
r.setFill(Color.LIGHTCYAN);

else if(a==1)
{
r.setFill(Color.DIMGREY);
}
else if(a==2)
{
r.setFill(Color.GOLD);
}
else if(a==3)
{
r.setFill(Color.AQUA);
}


}
});

}


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

}


OUTPUT:




1 comments: