Tuesday, 5 January 2021

JavaFX: Working with dialogs

‘javafx.scene.control.Dialog’ class used to define A Dialog instance in JavaFX, which wraps a DialogPane and provides the necessary API to present it to end users.

 

Information Dialog

 


Alert dialog = new Alert(AlertType.INFORMATION);
dialog.setTitle("Dialog Demo");
dialog.setWidth(100);
dialog.setHeight(50);
dialog.setHeaderText("Simple Dialog");
dialog.setContentText("You clicked on " + informationButton.getText() + " button");

 

Warning Dialog

 


Alert dialog = new Alert(AlertType.WARNING);
dialog.setTitle("Dialog Demo");
dialog.setWidth(100);
dialog.setHeight(50);
dialog.setHeaderText("Simple Dialog");
dialog.setContentText("You clicked on " + warningButton.getText() + " button");

Error Dialog




Alert dialog = new Alert(AlertType.ERROR);
dialog.setTitle("Dialog Demo");
dialog.setWidth(100);
dialog.setHeight(50);
dialog.setHeaderText("Simple Dialog");
dialog.setContentText("You clicked on " + errorButton.getText() + " button");


Error dialog with exception stack trace.





Confirmation Dialog

 

 


Alert dialog = new Alert(AlertType.CONFIRMATION);
dialog.setTitle("Dialog Demo");
dialog.setWidth(100);
dialog.setHeight(50);
dialog.setHeaderText("Simple Dialog");
dialog.setContentText("You clicked on " + confirmationButton.getText() + " button");

 

Find the below working application.

 

DialogDemo.java

package com.sample.app.diaogs;

import java.io.PrintWriter;
import java.io.StringWriter;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.stage.Stage;

public class DialogDemo extends Application {

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

	}

	Button getInformationButton() {
		Button informationButton = new Button("Information Dialog");
		informationButton.setAlignment(Pos.CENTER);
		informationButton.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		informationButton.setPadding(new Insets(10));
		informationButton.setStyle("-fx-background-color:salmon");

		informationButton.setOnAction(event -> {
			Alert dialog = new Alert(AlertType.INFORMATION);
			dialog.setTitle("Dialog Demo");
			dialog.setWidth(100);
			dialog.setHeight(50);
			dialog.setHeaderText("Simple Dialog");
			dialog.setContentText("You clicked on " + informationButton.getText() + " button");

			dialog.showAndWait();

		});

		return informationButton;
	}

	Button getWarningButton() {
		Button warningButton = new Button("Warning Dialog");
		warningButton.setAlignment(Pos.CENTER);
		warningButton.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		warningButton.setPadding(new Insets(10));
		warningButton.setStyle("-fx-background-color:orange");

		warningButton.setOnAction(event -> {
			Alert dialog = new Alert(AlertType.WARNING);
			dialog.setTitle("Dialog Demo");
			dialog.setWidth(100);
			dialog.setHeight(50);
			dialog.setHeaderText("Simple Dialog");
			dialog.setContentText("You clicked on " + warningButton.getText() + " button");

			dialog.showAndWait();

		});

		return warningButton;
	}

	Button getConfirmationButton() {
		Button confirmationButton = new Button("Confirmation Dialog");
		confirmationButton.setAlignment(Pos.CENTER);
		confirmationButton.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		confirmationButton.setPadding(new Insets(10));
		confirmationButton.setStyle("-fx-background-color:green");

		confirmationButton.setOnAction(event -> {
			Alert dialog = new Alert(AlertType.CONFIRMATION);
			dialog.setTitle("Dialog Demo");
			dialog.setWidth(100);
			dialog.setHeight(50);
			dialog.setHeaderText("Simple Dialog");
			dialog.setContentText("You clicked on " + confirmationButton.getText() + " button");

			dialog.showAndWait();

		});

		return confirmationButton;
	}

	Button getErrorButton() {
		Button errorButton = new Button("Error Dialog");
		errorButton.setAlignment(Pos.CENTER);
		errorButton.setFont(Font.font("Verdana", FontPosture.REGULAR, 30));
		errorButton.setPadding(new Insets(10));
		errorButton.setStyle("-fx-background-color:red");

		errorButton.setOnAction(event -> {
			Alert dialog = new Alert(AlertType.ERROR);
			dialog.setTitle("Dialog Demo");
			dialog.setWidth(100);
			dialog.setHeight(50);
			dialog.setHeaderText("Simple Dialog");
			dialog.setContentText("You clicked on " + errorButton.getText() + " button");

			Exception ex = new Exception("NullPointer Exception occured");

			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			ex.printStackTrace(pw);
			String exceptionText = sw.toString();

			Label label = new Label("The exception stacktrace is:");
			label.setFont(Font.font("Verdana", 15));
			label.setTextFill(Color.RED);

			TextArea textArea = new TextArea(exceptionText);
			textArea.setEditable(false);
			textArea.setWrapText(true);

			textArea.setMaxWidth(Double.MAX_VALUE);
			textArea.setMaxHeight(Double.MAX_VALUE);
			GridPane.setVgrow(textArea, Priority.ALWAYS);
			GridPane.setHgrow(textArea, Priority.ALWAYS);

			VBox vBox = new VBox();
			vBox.getChildren().addAll(label, textArea);
			vBox.setSpacing(10);
			vBox.setPadding(new Insets(10));

			// Set expandable Exception into the dialog pane.
			dialog.getDialogPane().setExpandableContent(vBox);

			dialog.showAndWait();

		});

		return errorButton;
	}

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

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

		HBox hBox1 = new HBox();
		Label label1 = new Label("Simple Dialog demo");
		label1.setFont(Font.font("Verdana", FontPosture.REGULAR, 45));
		hBox1.getChildren().add(label1);
		hBox1.setPadding(new Insets(20, 20, 20, 20));

		Button informationButton = this.getInformationButton();
		Button warningButton = this.getWarningButton();
		Button confirmationButton = this.getConfirmationButton();
		Button errorButton = this.getErrorButton();

		GridPane gridPane = new GridPane();
		gridPane.getChildren().addAll(informationButton, warningButton, confirmationButton, errorButton);
		gridPane.setConstraints(informationButton, 0, 0);
		gridPane.setConstraints(warningButton, 1, 0);
		gridPane.setConstraints(confirmationButton, 0, 1);
		gridPane.setConstraints(errorButton, 1, 1);
		gridPane.setPadding(new Insets(50));
		// gridPane.setStyle("-fx-background-color:lightsalmon");
		gridPane.setHgap(20);
		gridPane.setVgap(20);

		VBox vBox = new VBox();
		vBox.getChildren().addAll(hBox1, gridPane);
		vBox.setEffect(dropShadow);
		vBox.setStyle("-fx-background-color:azure");

		Scene scene = new Scene(vBox, 800, 500, Color.AZURE);

		primaryStage.setTitle("Dialog Demo 1");
		primaryStage.setScene(scene);
		primaryStage.show();
	}

}

 

Output

 

 


Click on a button to see respective dialog.




Click on ‘Show Details’ link to see complete stack trace.


 

Previous                                                    Next                                                    Home

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