Sunday, 27 December 2020

JavaFX: TableView widget

TableView class is used to define a table view control. TableView represent the data in rows and columns.

 

Is TableView scrollable?

Yes

 

Is TableView editable?

Yes

 

TableColumn

 

Find the below working application.

 

TableViewDemo.java

package com.sample.app.widgets;

import com.sample.app.model.Person;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

public class TableViewDemo extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {
		ObservableList<Person> emps = FXCollections.observableArrayList();

		emps.setAll(new Person(1, "Krishna"), new Person(2, "Ram"), new Person(3, "Joel"), new Person(4, "Gopi"),
				new Person(5, "Sharief"));

		Label label = new Label("Persons information");
		label.setFont(Font.font("Verdana", FontWeight.BOLD, 25));

		VBox vBox1 = new VBox(label);
		vBox1.setAlignment(Pos.CENTER);
		vBox1.setSpacing(20);

		VBox vBox2 = new VBox();

		TableColumn<Person, Integer> idColumn = new TableColumn<>("Id");
		idColumn.setMinWidth(50);
		idColumn.setCellValueFactory(new PropertyValueFactory<Person, Integer>("id"));

		TableColumn<Person, String> nameColumn = new TableColumn<>("Name");
		nameColumn.setMinWidth(50);
		nameColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("name"));

		TableView<Person> tableView = new TableView<>();
		tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		tableView.setItems(emps);
		tableView.setPrefHeight(250);
		tableView.getColumns().add(idColumn);
		tableView.getColumns().add(nameColumn);
		tableView.setPadding(new Insets(20));
		tableView.setEditable(true);

		DropShadow dropShadow = new DropShadow();
		dropShadow.setOffsetX(5);
		dropShadow.setOffsetY(5);
		dropShadow.setColor(Color.GRAY);

		tableView.setEffect(dropShadow);

		vBox2.getChildren().add(tableView);

		HBox hBox = new HBox();
		hBox.setSpacing(25);
		Label nameLabel = new Label("Change person name");
		nameLabel.setFont(Font.font("Verdana", 20));

		TextField textField = new TextField();

		textField.setOnAction(event -> {
			Person person = tableView.getSelectionModel().getSelectedItem();
			person.setName(textField.getText());
			tableView.refresh();
		});

		hBox.getChildren().addAll(nameLabel, textField);

		VBox buttonVBox = new VBox();
		buttonVBox.setAlignment(Pos.CENTER);
		Button removePerson = new Button("Remove");
		removePerson.setFont(Font.font("Verdana", 20));
		removePerson.setOnAction(event -> {
			Person person = tableView.getSelectionModel().getSelectedItem();
			tableView.getItems().remove(person);
			tableView.refresh();
		});
		buttonVBox.getChildren().add(removePerson);

		VBox vBox = new VBox(vBox1, vBox2, hBox, buttonVBox);
		vBox.setStyle("-fx-background-color:lightyellow");
		vBox.setPadding(new Insets(20));
		vBox.setSpacing(20);

		Scene scene = new Scene(vBox, 600, 500, Color.WHITE);

		primaryStage.setTitle("TableView Demo");
		primaryStage.setScene(scene);
		primaryStage.show();

	}

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

 

Output

  


 

Select a row and add some name in text field and enter, you will see new name will be reflected.

 

Select a row and click on Remove button, you will see that the row is deleted.

 

Previous                                                    Next                                                    Home

Python: Remove all the instances of a value from list

Using ‘while’ loop, we can delete all the instances of a value from the list.

 

Example

def remove_element(item, list):

    while(item in list):

         list.remove(item)

 

remove_elements.py

def remove_element(item, list):
    while(item in list):
    	list.remove(item)

data = [1, 2, 3, 4, 5, 3, 2, 2, 3, 4, 3]
print(f"data : {data}")

print("\nRemoving 3 from list")

remove_element(3, data)
print(f"\ndata : {data}")

 

Output

$python3 remove_elements.py
data : [1, 2, 3, 4, 5, 3, 2, 2, 3, 4, 3]

Removing 3 from list

data : [1, 2, 4, 5, 2, 2, 4]

 

 

  

Previous                                                    Next                                                    Home

Python: Convert string to an integer

‘int(string)’ function takes a string as argument and convert it to an integer.

>>> data = "2345"
>>> 
>>> data
'2345'
>>> 
>>> int(data)
2345

 

You will get an error while converting non-numerical data.

>>> data = "hh"
>>> 
>>> int(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hh'

 

 

 

Previous                                                    Next                                                    Home

Python: Dictionary in a dictionary

dict_in_dict.py

country_capitals = {"India" : "New Delhi", "Bangladesh" : "Dhaka", "France" : "Paris"}
numbers = {1 : "One", 2: "Two"}

my_dictionary = {"countryCapitals": country_capitals, "numbers" : numbers}

for key in my_dictionary.keys():
	print(f"{key} -> {my_dictionary[key]}")

 

Output

$ python3 dict_in_dict.py 
countryCapitals -> {'India': 'New Delhi', 'Bangladesh': 'Dhaka', 'France': 'Paris'}
numbers -> {1: 'One', 2: 'Two'}

 

 

 

 

 

Previous                                                    Next                                                    Home

Python: List in a dictionary

In this post, I am going to explain how to add a list to the dictionary.

 

list_in_dictionary.py

dict = {1 : "One"}
even_numbers = [2, 4, 6, 8]
odd_numbers = [1, 3, 5, 7]

my_dictionary = {"dict": dict, "evenNumbers" : even_numbers, "oddNumbers" : odd_numbers}

for key in my_dictionary.keys():
	print(f"{key} -> {my_dictionary[key]}")

 

Output

$ python3 list_in_dictionary.py 
dict -> {1: 'One'}
evenNumbers -> [2, 4, 6, 8]
oddNumbers -> [1, 3, 5, 7]

 

 

 

 

Previous                                                    Next                                                    Home

Python: List of dictionaries

In this post, I am going to explain how to create list of dictionaries.

 

list_of_dictionary.py

dict1 = {"a" : "A", "b" : "B"}
dict2 = {1 : "One", 2 : "Two"}
country_capitals = {"India" : "New Delhi", "Bangladesh" : "Dhaka", "France" : "Paris"}

list = [dict1, dict2, country_capitals]

for item in list:
	print(f"{item}")

Output

$ python3 list_of_dictionary.py {'a': 'A', 'b': 'B'} {1: 'One', 2: 'Two'} {'India': 'New Delhi', 'Bangladesh': 'Dhaka', 'France': 'Paris'}

 

 

 


 

 

Previous                                                    Next                                                    Home

Python: Looping through all values in a dictionary

‘values’ method is used to loop through all the values in a dictionary.

>>> country_capitals = {"India" : "New Delhi", "Bangladesh" : "Dhaka", "France" : "Paris"}
>>> 
>>> for capital in country_capitals.values():
...   print(f"{capital}")
... 
New Delhi
Dhaka
Paris

 

 

Previous                                                    Next                                                    Home

Python: Looping through the dictionary in the sorted order of keys

Using ‘sorted’ and ‘keys’ methods, you can loop through the dictionary in the sorted order of dictionary keys.

>>> country_capitals = {"India" : "New Delhi", "Bangladesh" : "Dhaka", "France" : "Paris"}
>>> 
>>> for country in sorted(country_capitals):
...    print(f"{country} -> {country_capitals[country]}")
... 
Bangladesh -> Dhaka
France -> Paris
India -> New Delhi

 

 

Previous                                                    Next                                                    Home

Python: Looping over a dictionary using keys

Using keys() method

‘keys()’ method return an iterator over all the keys of a dictionary.

 

Example

for key in emps.keys():

    print(f"{key} : {emps[key]}")

>>> emps = {1: {'Hari Krishna', 'Gurram'}, 3: {'Shekkappa', 'Mohan'}, 4: {'Ranganath', 'Thippisetty'}, 5: {'Ganji', 'Sudheer'}}
>>> 
>>> for key in emps.keys():
...   print(f"{key} : {emps[key]}")
... 
1 : {'Gurram', 'Hari Krishna'}
3 : {'Mohan', 'Shekkappa'}
4 : {'Thippisetty', 'Ranganath'}
5 : {'Sudheer', 'Ganji'}

 

 

 

Previous                                                    Next                                                    Home

Python: Check list emptiness using if condition

‘if list_name’

 

Syntax

if list_name:
    # List is not empty
else:
   # List is empty

 

Example

if list:
	for elem in list:
		print(elem)
	else:
		print("List is empty\n")

 

list_emptycheck.py

# Print elements of list
def print_elements(list):
   if list:
      for elem in list:
         print(elem)
   else:
      print("List is empty\n")

primes = []
print_elements(primes)

primes.append(2)
primes.append(3)
primes.append(5)
print_elements(primes)

Output

$ python3 list_empty_check.py 
List is empty

2
3
5


 

Previous                                                    Next                                                    Home

Python: not in: Check for non-existence of element in the list

‘not in’ keyword is return True, if given element is not in the list, else False.

 

Syntax

element not in list

 

Example

10 not in first_5_primes

 

Above statement return True, if 10 is not in the list first_5_primes, else False.

 

Example

10 not in first_5_primes

>>> first_5_primes = [2, 3, 5, 7, 11]
>>> 
>>> 10 not in first_5_primes
True
>>> 
>>> 11 not in first_5_primes
False
>>>

 

 

Previous                                                    Next                                                    Home