JavaFX ListView

 

ListView

§  Controls such as check boxes and radio buttons are very useful for representing a small, fixed number of options.

§  For larger number of options – ListView offers a better solution.

§  The ListView class encapsulates a list view.

§  List views are controls that display a list of entries from which user can select one or more values.

§  The number of entries in the list can increase or decrease during the execution of the program.

§  They also make efficient use of limited screen space.

§  ListView is a generic class that is declared like this:

          class ListView<T>

§  Here, T specifies the type of entries stored in the list view.

 

§  ListView defines two constructors.

o   default constructor, which creates an empty ListView.

o   can specify the list of entries in the list.

     ListView(ObservableList<T> list)

 

§  list specifies a list of the items that will be displayed.

§  It is an object of type ObservableList, which defines a list of observable objects.

§  ObservableList inherits java.util.List.

§  it supports the standard list collection methods.

§  ObservableList is packaged in javafx.collections.

§  To create an ObservableList for use in a ListView – use the factory method observableArrayList( ), – static method defined by the FXCollections class

     static <E> ObservableList<E> observableArrayList( E … elements)

§  Here, E specifies the type of elements, which are passed via elements.

 

§  Other methods

§  to set the preferred height and/or width – setPrefHeight( ) and setPrefWidth( )

     final void setPrefHeight(double height)

     final void setPrefWidth(double width)

§  to set both dimensions at the same time – setPrefSize( )

     void setPrefSize(double width, double height)

§  ListView will automatically provide scroll bars when the number of items in the list exceed the size of the control.


 

§  Number of items that can be selected –

o   By default – allows only one item

o   to enable multiple selections – change the selection mode.

§  Method to find the selection mode – getSelectionModel( )

o   final MultipleSelectionModel<T> getSelectionModel( )

 

§  There are two basic ways in which you can use a ListView.

o   First, you can ignore events generated by the list and simply obtain the selection in the list when your program needs it.

o   Second, you can monitor the list for changes by registering a change listener.

§  This lets you respond each time the user changes a selection in the list.

 

§  To listen for change events,

o   obtain the selection model used by the ListView.

o   identify the list item selected –

§  obtain a reference to the item, or obtain its index.

§  reference to the item

1.    get the selectedItemProperty.

2.    This property defines what takes place when an element in the list is selected.

          final ReadOnlyObjectProperty<T> selectedItemProperty( )

3.    add the change listener to this property

a.    by calling addListener( ) on the property and

b.    passing in the change listener.

 


§  Changing the ListView Dynamically

§  Once a list has been created, you can add to or remove items from it by adding or removing them from the ObservableList that backs it. To add an item, use add( ). To add a list of items, use addAll( ). To remove an item, use remove( ). Various forms of these methods are supported. Making a change to an ObservableList results in the same change in the ListView that uses the list. For example, the following lines add Red Delicious to the list and remove Fuji from the ListViewDemo program.

 

§  In this example, the name of the backing list appleTypes is known, so it is used explicitly. However, it is possible to obtain a reference to the backing list from the ListView control, itself. This is done by calling getItems( ) on the ListView instance. It is shown here:

§  final ObservableList<T> getItems( )

§  It returns a reference to the backing list. Using getItems( ), the previous statements can be rewritten like this:

 

§  One other point: you can set the backing list after the ListView instance has been created by using

§  setItems( ):

§  final void setItems(ObservableList<T> itemList) Here, itemList is a reference to the new backing list.

§  Obtaining ListView Item Indices

§  As mentioned earlier, when listening for change events on a ListView, you can identify what item was selected by obtaining a reference to it or by obtaining its index in the list. The first approach was shown by the preceding examples. Here, we will look at using indices. Although the two processes are similar, different methods are needed.

§  To obtain the index of a selected item when a change event occurs, first obtain the selection model by calling getSelectionModel( ) on the list, as before. Then, using this model, obtain a reference to the selected index property by calling selectedIndexProperty( ), shown next:

§  final ReadOnlyIntegerProperty selectedIndexProperty( )

§  Notice that this method returns a ReadOnlyIntegerProperty. This is because the index of a selection is represented by an integer value. Next, add a change listener to the object returned by selectedIndexProperty( ). For example,

§  a list of the selected indices by calling getSelectedIndices( ) on the selection model. You might want to try this on your own.

 


 

// JavaFX Controls

// ListView

 

import javafx.application.*;

import javafx.scene.*;

import javafx.stage.*;

import javafx.event.*;

import javafx.scene.layout.*;

import javafx.scene.control.*;

import javafx.scene.input.*;

import javafx.scene.text.*;

import javafx.geometry.*;

import javafx.beans.value.*;

import javafx.collections.*;

 

public class JfxChk extends Application

{

   public static void main(String []args)

   {

        launch(args);    

   }

  

   public void init(){}

   public void stop(){}

  

   public void start(Stage myStage)

   {

        myStage.setTitle("JavaFX - ListView");

  

        FlowPane fp = new FlowPane(Orientation.VERTICAL,15,15);

        fp.setAlignment(Pos.CENTER);

       

        Label L1 = new Label();

        Label L2 = new Label();

       

        // Create list and add it to ViewList

        ObservableList<String> dept = FXCollections.observableArrayList(

"IT","CSE", "CIVIL", "MECH", "Others");

        ListView<String> lv = new ListView<String>(dept);

        lv.setPrefSize(100,75);

       

        lv.getItems().add("AUTO");

        lv.getItems().remove("Others");

       

        MultipleSelectionModel<String> lvsel = lv.getSelectionModel();

       

        // Event Handling – ChangeListener - Item

        lvsel.selectedItemProperty().addListener(new ChangeListener<String>()

        {

             public void changed(ObservableValue<? extends String> changed,

String oldval, String newval)

             {

                 L1.setText("Selected department is "+newval);

             }

        });

       

        // Event Handling – ChangeListener - Index

        lvsel.selectedIndexProperty().addListener(new ChangeListener<Number>()

        {

             public void changed(ObservableValue<? extends Number> changed,

Number oldval, Number newval)

             {

                 L2.setText("Index of department is "+newval);

             }

        });

       

        fp.getChildren().addAll(lv, L1, L2);

       

        Scene myScene = new Scene(fp, 300, 200);

        myStage.setScene(myScene);

        myStage.show();

   }

}

 


 

// JavaFX Controls

// ListView

// Multiple selection

 

import javafx.application.*;

import javafx.scene.*;

import javafx.stage.*;

import javafx.event.*;

import javafx.scene.layout.*;

import javafx.scene.control.*;

import javafx.scene.input.*;

import javafx.scene.text.*;

import javafx.geometry.*;

import javafx.beans.value.*;

import javafx.collections.*;

 

public class JfxChk extends Application

{

          public static void main(String []args)

          {

                   launch(args);         

          }

         

          public void init(){}

          public void stop(){}

         

          public void start(Stage myStage)

          {

                   myStage.setTitle("JavaFX - ListView");

         

                   FlowPane fp = new FlowPane(Orientation.VERTICAL,15,15);

                   fp.setAlignment(Pos.CENTER);

                  

                   Label L1 = new Label();

                   Label L2 = new Label();

                  

                   // Create list and add it to ViewList

                   ObservableList<String> dept = FXCollections.observableArrayList(

"IT","CSE", "CIVIL", "MECH", "Others");

                   ListView<String> lv = new ListView<String>(dept);

                   lv.setPrefSize(100,75);

                                     

                   MultipleSelectionModel<String> lvsel = lv.getSelectionModel();

                   lvsel.setSelectionMode(SelectionMode.MULTIPLE);

                  

                   // Event Handling – ChangeListener - Item

                   lvsel.selectedItemProperty().addListener(new ChangeListener<String>()

                   {

                             public void changed(ObservableValue<? extends String> changed,

String oldval, String newval)

                             {

                                      StringBuffer str = new StringBuffer();

                                      ObservableList<String> selvalues = lvsel.getSelectedItems();

                                     

                                      for(String s:selvalues)

                                                str.append(s+" ");

                                     

                                      L1.setText("Selected department is "+str.toString());

                             }

                   });

                  

                   fp.getChildren().addAll(lv, L1);

                  

                   Scene myScene = new Scene(fp, 300, 200);

                   myStage.setScene(myScene);

                   myStage.show();

          }

}

 



 


 


 

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu