Pesquisar neste blog

06/05/2020

Dia da semana com switch case no JavaScript

var agora = new Date()
var diaSem = agora.getDay()//dia da semana que é agora

console.log(diaSem)
switch(diaSem){
    case 0:
        console.log('Domingo')
        break
    case 1:
        console.log('Segunda - feira')
        break
    case 2:
        console.log('Terça - feira'
        break
    case 3:
        console.log('Quarta - feira')
        break
    case 4:
        console.log('Quinta - feira')
        break
    case 5:
        console.log('Sexta - feira')
        //break
    case 6:
        console.log('Sábado')
        break
    default:
        console.log('[Erro] Dia inválido!')
        break                           
}


Data e hora no JavaScript

var agora = new Date()
var hora = agora.getHours()//hora do do servidor

console.log('Data de hoje = '+agora.getUTCDate()+'/'+agora.getUTCMonth()+'/'+agora.getFullYear())
console.log('Agora são '+hora+':'+agora.getMinutes()+' horas')


05/05/2020

Cadastro de produtos no Java com interface

package cadastro;

/**
 *
 * @author Aluno
 */
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.ChoiceBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.regex.Pattern;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.stage.FileChooser.ExtensionFilter;

public class TabForm extends Application {

 BorderPane bdp;

 //Área Superior do BorderPane
 Label lblOption, lblKeyword;
 TextField txtKeyword;
 ChoiceBox chbOption; //para escolher por qual campo pesquisar
 HBox pnlSearch;
 FadeTransition ft; //para animar os componentes de busca

 //Área Central do BorderPane
 TabPane tbp; //componente de abas
 Tab tabSearch, tabEdit; //aba de busca e aba de edição
 //Conteúdo da aba de busca
 TableView tbl;
 ContextMenu ctxMenu; //permite ativar menu com botão direito
 MenuItem mnuEdit, mnuDelete; //3 opções de menu do botão direito

 //Conteúdo da Aba de Edição
 GridPane gridEdit; //o formulário será organizado em um Grid (matriz)
 Label lblName, lblQtty, lblPrice, lblType, lblQttyError;
 TextField txtName, txtQtty, txtPrice;
 ChoiceBox chbType;
 final FileChooser fc = new FileChooser(); //para escolher o arquivo da imagem
 Button btnSelectPicture;
 final ImageView imgProduct = new ImageView(); //para exibir a imagem escolhida

 //Área Inferior do BorderPane
 HBox pnlBottom;
 Button btnNew, btnConfirm, btnEdit, btnCancel, btnDelete;

 @SuppressWarnings("unchecked")
 @Override
 public void start(Stage primaryStage) {
   primaryStage.setTitle("Tab Form");
   bdp = new BorderPane();
   Scene scene = new Scene(bdp, 500, 400);

   //Construindo a área superior
   lblKeyword = new Label("Keyword:");
   lblKeyword.setOpacity(0);
   txtKeyword = new TextField();
   txtKeyword.setOpacity(0);
   txtKeyword.setTooltip(new Tooltip("Press ENTER to Search!")); //dica
   txtKeyword.setPromptText("Type what to search here");
   txtKeyword.setPrefColumnCount(13);
   txtKeyword.setStyle(Style.BUTTON);
   txtKeyword.setOnKeyPressed(e -> { txtKeyword_onKeyPressed(e); });
   lblOption= new Label("Option:");
   lblOption.setOpacity(0);
   chbOption = new ChoiceBox();
   chbOption.setOpacity(0);
   chbOption.setOnAction(e -> { chbOption_onAction((ActionEvent) e); });
   chbOption.getItems().addAll("Name", "Type");
   chbOption.getSelectionModel().selectFirst();

   pnlSearch = new HBox(5); //Espaço de 5 px
   pnlSearch.setAlignment(Pos.CENTER);
   pnlSearch.getChildren().addAll(lblKeyword, txtKeyword, lblOption, chbOption);
   pnlSearch.setPadding(new Insets(5));

   ft = new FadeTransition(Duration.millis(700));
   ft.setFromValue(0.0);
   ft.setToValue(1.0);
   ft.setNode(lblKeyword);
   ft.setOnFinished(e->{ ft_onFinished(e); });   

   //Construindo a área inferior
   btnNew = new Button("New");
   btnNew.setStyle(Style.BUTTON);
   btnNew.setOnAction(e -> { btnNew_onAction(e); });
   btnConfirm = new Button("Confirm");
   btnConfirm.setStyle(Style.BUTTON);
   btnConfirm.setOnAction(e -> { btnConfirm_onAction(e); });
   btnEdit = new Button("Edit");
   btnEdit.setTooltip(new Tooltip("Shortcut: CMD+E"));
   btnEdit.setStyle(Style.BUTTON);
   btnEdit.setOnAction(e -> { btnEdit_onAction(e); });
   btnCancel = new Button("Cancel");
   btnCancel.setStyle(Style.BUTTON);
   btnCancel.setOnAction(e -> { btnCancel_onAction(e); });
   btnDelete = new Button("Delete");
   btnDelete.setTooltip(new Tooltip("Shortcut: CMD+D"));
   btnDelete.setStyle(Style.BUTTON);
   btnDelete.setOnAction(e -> { btnDelete_onAction(e); });        

   //Tecla de atalho para realizar busca (CTRL + S)
   scene.getAccelerators().put(
     new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN), 
       new Runnable() {
         @Override public void run() {
           txtKeyword.requestFocus();
         }
       }
   );

   //Tecla de atalho para seleção da tabela (CTRL + T)
   scene.getAccelerators().put(
   new KeyCodeCombination(KeyCode.T, KeyCombination.SHORTCUT_DOWN), 
     new Runnable() {
       @Override public void run() {
         tbl.requestFocus();
       }
     }
   );

   //Tecla de atalho para exclusão (CTRL + D)
   scene.getAccelerators().put(
     new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN), 
       new Runnable() {
         @Override public void run() {
           btnDelete.fire();
         }
       }
   );

   //Tecla de atalho para edição (CTRL + E)
   scene.getAccelerators().put(
     new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN), 
       new Runnable() {
         @Override public void run() {
           btnEdit.fire();
         }
       }
   );

   //botões da parte inferior da interface
   pnlBottom = new HBox(5);
   pnlBottom.setAlignment(Pos.CENTER);
   pnlBottom.getChildren().addAll(btnNew, btnConfirm, btnEdit, btnCancel, btnDelete);
   pnlBottom.setPadding(new Insets(5));

   //Construindo a Aba Busca
   //Lista de produtos que serão exibidos na tabela
   final ObservableList produtos = FXCollections.observableArrayList(
     new Product("Wine",ProductType.BEVERAGE,new BigDecimal(40),10),
     new Product("Soap",ProductType.CLEAN,new BigDecimal(8),5),
     new Product("Cristal Clean",ProductType.CLEAN,new BigDecimal(5),25),
     new Product("Soda",ProductType.BEVERAGE,new BigDecimal(3),43)
   );

   //Configurando a coluna nome do produto
   TableColumn tbcName = new TableColumn<>("Name");
   tbcName.setCellValueFactory(new PropertyValueFactory("name"));

   //permitindo que as células da coluna nome sejam editáveis
   tbcName.setCellFactory(TextFieldTableCell.forTableColumn());
   tbcName.setOnEditCommit(
     new EventHandler<CellEditEvent<Product, String>>() {
       @Override
       public void handle(CellEditEvent<Product, String> t) {
         ((Product) t.getTableView().getItems().get(
           t.getTablePosition().getRow())
         ).setName(t.getNewValue());
       }
     }
   );        

   //Configurando a coluna tipo do produto
   TableColumn tbcType = new TableColumn<>("Type");
   tbcType.setCellValueFactory(new PropertyValueFactory("type"));

   //permitindo que as células da coluna tipo sejam editáveis
 tbcType.setCellFactory(ChoiceBoxTableCell.forTableColumn(ProductType.values()));
   tbcType.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Product,ProductType>>() {
     @Override
     public void handle(CellEditEvent<Product, ProductType> t) {
       ((Product) t.getTableView().getItems().get(
         t.getTablePosition().getRow())
       ).setType(t.getNewValue());    
     }
   });                

   //Configurando a coluna preço do produto
   TableColumn tbcPrice = new TableColumn<>("Price");
   tbcPrice.setCellValueFactory(new PropertyValueFactory("price"));

   //Configurando a coluna qtde do produto
   TableColumn tbcQtty = new TableColumn<>("Qtty");
   tbcQtty.setCellValueFactory(new PropertyValueFactory("qtty"));

   //Configurando a coluna para mostrar a imagem do produto
   TableColumn tbcImg = new TableColumn<>("Image");
   tbcImg.setCellValueFactory(new PropertyValueFactory("img"));

   //Criando a tabela
   tbl = new TableView();
   //Definindo uma dica sobre a possibilidade de usar o botão direito do mouse
   tbl.setTooltip(new Tooltip("Press the right button of the mouse for more options!"));
   tbl.setPrefHeight(300);
   tbl.setItems(produtos); //de onde obterá a lista de produtos

   //adicionando as colunas previamente configuradas
   tbl.getColumns().addAll(tbcName, tbcType, tbcPrice, tbcQtty, tbcImg);
   //não permite o redimensionamento das colunas pelo usuário
   tbl.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

   //Estilo visual da tabela
   tbl.setStyle(Style.TABLE);
   tbl.setOnMouseClicked(e -> { tbl_onMouseClicked(e); });
   tbl.setOnKeyPressed(e -> { tbl_onKeyPressed(e); });
   tbl.setEditable(true); //tabela permite edição

   //Configurando o menu do botão direito do mouse sobre a tabela
   ctxMenu = new ContextMenu();
   mnuEdit = new MenuItem("Edit");
   mnuEdit.setOnAction(e -> { mnuEdit_onAction(e); });
   mnuDelete = new MenuItem("Delete");
   mnuDelete.setOnAction(e -> { mnuDelete_onAction(e); });
   ctxMenu.getItems().addAll(mnuEdit, mnuDelete);
   tbl.setContextMenu(ctxMenu);        

   //Construindo a aba de edição
   lblName = new Label("Name:");
   lblName.setMinWidth(70);
   lblType = new Label("Type:");
   lblQtty = new Label("Qtty:");
   lblQttyError = new Label("");lblQttyError.setTextFill(Color.RED);
   lblQttyError.setStyle("-fx-font-size: 11px;");
   lblPrice = new Label("Price:");

   txtName = new TextField();
   txtName.setPromptText("Product description");
   txtName.setMinWidth(200);
   txtName.setPrefWidth(300);
   chbType = new ChoiceBox<>();
   for (ProductType pt : ProductType.values())
     chbType.getItems().add(pt);
   txtQtty = new TextField();
   txtQtty.setMinWidth(30);
   txtQtty.setPrefWidth(50);
   txtQtty.setMaxWidth(70);

   txtPrice = new TextField();
   txtPrice.setMinWidth(30);
   txtPrice.setPrefWidth(50);
   txtPrice.setMaxWidth(100);

   btnSelectPicture = new Button("Select Picture");
   btnSelectPicture.setOnAction(e -> {
     btnSelect_onPicture(e, primaryStage);
   });

   //Configurando o componente de seleção de imagem
   fc.setTitle("Select Product Image");
   //Somente serão aceitas extensões PNG, JPG e GIF
   fc.getExtensionFilters().addAll(
     new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")
   );

   imgProduct.setFitWidth(100);
   imgProduct.setFitHeight(100);
   imgProduct.setPreserveRatio(true); //deve preservar a proporção da imagem

   //Configurando a matriz aonde ficarão os elementos da aba edição
   gridEdit = new GridPane();

   gridEdit.setAlignment(Pos.CENTER);
   gridEdit.setHgap(10); gridEdit.setVgap(10);     
   gridEdit.setPadding(new Insets(25, 25, 25, 25));

   gridEdit.add(lblName, 0, 0); //coluna 0, linha 0
   gridEdit.add(txtName, 1, 0); //coluna 1, linha 0
   gridEdit.add(lblType, 0, 1); //coluna 0, linha 1
   gridEdit.add(chbType, 1, 1); //coluna 1, linha 1
   gridEdit.add(lblQtty, 0, 2); //...
   gridEdit.add(txtQtty, 1, 2);
   gridEdit.add(lblQttyError, 2, 2);
   gridEdit.add(lblPrice, 0, 3);
   gridEdit.add(txtPrice, 1, 3);
   gridEdit.add(btnSelectPicture, 0, 4);
   gridEdit.add(imgProduct, 1, 4);

   //Juntando tudo
   tabSearch = new Tab("Products");
   tabSearch.setOnSelectionChanged(e -> {tabSearch_onSelectionChange(e); });
   tabSearch.setClosable(false);  //aba não permite ser fechada
   tabSearch.setContent(tbl); //conteúdo dessa aba é uma tabela

   tabEdit = new Tab("Edit");
   tabEdit.setOnSelectionChanged(e -> {tabEdit_onSelectionChange(e); });
   tabEdit.setClosable(false); //aba não permite ser fechada
   tabEdit.setContent(gridEdit); //conteúdo dessa aba é um painel

   tbp = new TabPane();
   tbp.getTabs().addAll(tabSearch, tabEdit); //somente duas abas

   bdp.setTop(pnlSearch); //no topo da interface o painel de busca
   bdp.setCenter(tbp);    //no centro o painel com 2 abas
   bdp.setBottom(pnlBottom); //na parte inferior o painel com os botões

   primaryStage.setScene(scene);
   primaryStage.show();
   tbl.requestFocus();
   setEditable(false); //formulário não pode ser editado inicialmente
   ft.play(); //fazendo aparecer gradualmente os componentes de busca
 }

 private void btnSelect_onPicture(ActionEvent e, Stage stage) {
   File f = fc.showOpenDialog(stage);
   if (f != null){
     imgProduct.setImage(new Image(f.toURI().toString()));
   }
 }
 
 //se pressionar ENTER na tabela é como clicar no botão editar
 private void tbl_onKeyPressed(KeyEvent e) {
   if (e.getCode()==KeyCode.ENTER)
     btnEdit.fire();
 }

 //algoritmo da animação do painel de busca (parte superior)
 private void ft_onFinished(ActionEvent e) {
   if (ft.getNode()==lblKeyword) {
     ft.setNode(txtKeyword);
     ft.play();
   }else if (ft.getNode()==txtKeyword) {
     ft.setNode(lblOption);
     ft.play();
   }else if (ft.getNode()==lblOption) {
     ft.setNode(chbOption);
     ft.play();
   }else if(ft.getNode()==chbOption){
     txtKeyword.requestFocus();
   }
 }

 //Verifica se a aba pode ser mudada (em edição não pode)
 private void tabSearch_onSelectionChange(Event e) {
   if (tabSearch.isSelected() && btnNew.isDisabled()) {
     tbp.getSelectionModel().select(tabEdit);
     Alert alert = new Alert(AlertType.INFORMATION);
     alert.setTitle("Information Dialog");
     alert.setHeaderText("Search not Allowed!");
     alert.setContentText("You are editing a register. You have to CONFIRM or CANCEL your operation.");
     alert.showAndWait();
   }
 }

 //quando muda para a aba de edição os campos são preenchidos
 private void tabEdit_onSelectionChange(Event e) {
   if (tabEdit.isSelected()) {
     fillForm();
   }
 }
 
 //Se der um duplo clique na tabela vai para a aba de edição
 private void tbl_onMouseClicked(MouseEvent e) {
   if (e.getClickCount()>=2) {
     tbp.getSelectionModel().select(1);
   }
 }

 private void mnuDelete_onAction(ActionEvent e) {
   btnDelete_onAction(e);
 }

 private void mnuEdit_onAction(ActionEvent e) {
   btnEdit_onAction(e);
 }

 //Se mudar o choice da busca vai para a aba de busca
 private void chbOption_onAction(ActionEvent e) {
   if (tbp!=null) tbp.getSelectionModel().select(0);
 }

 //Se pressionar ENTER na caixa de texto de busca vai para a aba de busca
 private void txtKeyword_onKeyPressed(KeyEvent e) {
   if (e.getCode() == KeyCode.ENTER) {
     tbp.getSelectionModel().select(0);
   }
 }

 private void btnDelete_onAction(ActionEvent e) {
   Alert alert;
   Product p = (Product) tbl.getSelectionModel().getSelectedItem();
   if (p != null) {
     alert = new Alert(AlertType.CONFIRMATION);
     alert.setTitle("Confirmation Dialog");
     alert.setHeaderText("DELETE Dialog");
     alert.setContentText("Are you sure you want to delete it?");

     Optional result = alert.showAndWait();
     if (result.get() == ButtonType.OK){
       tbl.getItems().remove(p);
       clearForm();
     }
   } else {
     alert = new Alert(AlertType.INFORMATION);
     alert.setTitle("Information Dialog");
     alert.setHeaderText("Product not selected!");
     alert.setContentText("You must select a product in the table in order to delete.");
     alert.showAndWait();   
   }
 }

 private void btnCancel_onAction(ActionEvent e) {
   setEditable(false);
   clearForm();
   fillForm();
 }

 private void btnEdit_onAction(ActionEvent e) {
   Alert alert;
   Product p = (Product) tbl.getSelectionModel().getSelectedItem();
   if (p!=null) {
     setEditable(true);
     tbp.getSelectionModel().select(1);
     txtName.requestFocus();
   } else {
     alert = new Alert(AlertType.INFORMATION);
     alert.setTitle("Information Dialog");
     alert.setHeaderText("Product not selected!");
     alert.setContentText("You must select a product in the table in order to edit it.");
     alert.showAndWait();      
   }
 }

 private void btnConfirm_onAction(ActionEvent e) {
  boolean error = false;
  if (!Pattern.matches("[0-9]*\\.?[0-9]*", txtQtty.getText())){
   txtQtty.setStyle(Style.ERROR);
   lblQttyError.setText("Value must be a number >= 0");
   error=true;
   txtQtty.requestFocus();
  }

  if (!error) {
    Product p = (Product) tbl.getSelectionModel().getSelectedItem();
    if (p == null) {
      p = new Product();
      tbl.getItems().add(p);
    }
    p.setName(txtName.getText());
    p.setPrice(new BigDecimal(txtPrice.getText()));
    p.setQtty(new Float(txtPrice.getText()));
    p.setType((ProductType) chbType.getSelectionModel().getSelectedItem());
    ImageView iv = new ImageView(imgProduct.getImage());
    iv.setFitWidth(100);
    iv.setFitHeight(100);
    iv.setPreserveRatio(true);
    p.setImg(iv);
    clearForm();
    setEditable(false);
    tbl.refresh();
    tbp.getSelectionModel().select(0);
    tbl.requestFocus();
    tbl.getSelectionModel().select(p);
  }
 }

 private void btnNew_onAction(ActionEvent e) {
   setEditable(true);
   tbp.getSelectionModel().select(1);
   clearForm();
   txtName.requestFocus();
   tbl.getSelectionModel().select(null);
 }

 public void setEditable(boolean edit) {
   btnNew.setDisable(edit);
   btnConfirm.setDisable(!edit);
   btnEdit.setDisable(edit);
   btnCancel.setDisable(!edit);
   btnDelete.setDisable(edit);
   gridEdit.setDisable(!edit);
 }

 public void clearForm() {
   txtName.setText("");
   txtQtty.setText("");
   txtPrice.setText("");
   chbType.getSelectionModel().select(-1);
   txtName.setStyle("");
   txtQtty.setStyle("");
   txtPrice.setStyle("");
   //imgProduct.setImage(null); it doesn't work properly
   lblQttyError.setText("");
 }

 public void fillForm() {
  Product p = (Product) tbl.getSelectionModel().getSelectedItem();
  if (p!=null) {
   txtName.setText(p.getName());
   txtQtty.setText(p.getQtty()+"");
   txtPrice.setText(p.getPrice().toString());
   chbType.getSelectionModel().select(p.getType());
   imgProduct.setImage(p.getImg().getImage());
  }
 }

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

 public static class Product {
     private String name;
     private ProductType type;
     private BigDecimal price;
     private float qtty;
     private ImageView img = new ImageView(new Image(getClass().getResourceAsStream("search.png")));

     public Product() {}
     public Product(String name, ProductType type, BigDecimal price, float qtty) {
      this.name = name;
      this.type = type;
      this.price = price;
      this.qtty = qtty;
     }

  public String getName() {
   return name;
  }

  public void setName(String name) {
   this.name = name;
  }

  public ProductType getType() {
   return type;
  }

  public void setType(ProductType type) {
   this.type = type;
  }

  public BigDecimal getPrice() {
   return price;
  }

  public void setPrice(BigDecimal price) {
   this.price = price;
  }

  public float getQtty() {
   return qtty;
  }

  public void setQtty(float qtty) {
   this.qtty = qtty;
  }

  @Override
  public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((name == null) ? 0 : name.hashCode());
   result = prime * result + ((type == null) ? 0 : type.hashCode());
   return result;
  }

  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   Product other = (Product) obj;
   if (name == null) {
    if (other.name != null)
     return false;
   } else if (!name.equals(other.name))
    return false;
   if (type != other.type)
    return false;
   return true;
  }

  public String toString() {
      return "Product: " + name;
  }
  public ImageView getImg() {
   return img;
  }
  public void setImg(ImageView img) {
   this.img = img;
  }
}

public static enum ProductType {
  BEVERAGE, CLEAN, FOOD
}

public static class Style {
  public static final String BUTTON = "-fx-background-color: linear-gradient(#ffd65b, #e68400), linear-gradient(#ffef84, #f2ba44), linear-gradient(#ffea6a, #efaa22), linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%), linear-gradient(from 0% 0% to 15% 50%, rgba(255,255,255,0.9), rgba(255,255,255,0)); -fx-background-radius: 10;   -fx-background-insets: 0,1,2,3,0;  -fx-text-fill: #654b00;     -fx-font-weight: bold;     -fx-font-size: 12px;     -fx-padding: 10 10 10 10;";
  public static final String ERROR = "-fx-background-color: red,linear-gradient(to bottom, derive(red,60%) 5%,derive(red,90%) 40%);";
  public static final String TABLE = "-fx-selection-bar: orange; -fx-selection-bar-non-focused: moccasin;";
 }
    
}

Vetor em JavaScript

Array.prototype.filter2 = function(callback) {
    const newArray = []
    for (let i = 0i < this.lengthi++) {
        if(callback(this[i], ithis)) {
            newArray.push(this[i])
        }
    }
    return newArray
}

const produtos = [
    { nome: 'Notebook'preco: 2499fragil: true },
    { nome: 'iPad Pro'preco: 4199fragil: true },
    { nome: 'Copo de Vidro'preco: 1249fragil: true },
    { nome: 'Copo de Plástico'preco: 18.99fragil: false }
]

const caro = produto => produto.preco >= 500
const fragil = produto => produto.fragil

console.log(produtos.filter2(caro).filter2(fragil))


Circulo animado em Java

package animandoShape;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author HENRIQUE
 */
public class AnimatedCircle extends Application implements Runnable{
    
    Circle circle = new Circle(40);
    Stage stage;
    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;
        Pane pane = new Pane();
        circle.setCenterX(40);
        circle.setCenterY(40);
        pane.getChildren().add(circle);
        Scene scene = new Scene(pane,800,600);
        stage.setScene(scene);
        stage.show();
        Thread t = new Thread(this);
        t.setDaemon(true);
        t.start();
    }
    @Override
    public void run() {
        boolean forward = true;
        while (true) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (circle.getTranslateX()>=stage.getWidth()-80) forward=false;
            if (circle.getTranslateX()<=0) forward=true;
            if (forward)
                circle.setTranslateX(circle.getTranslateX()+5);
            else
                circle.setTranslateX(circle.getTranslateX()-5);
        }
    }
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}

Desenhando arco iris em Java

Utilizando: JavaSwing e Javax

Classe DesenharArcoIris

package arcoiris;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class ClasseDesenharArcoIris extends JPanel{
    //define as cores indigo e violeta
    private final static Color VIOLET = new Color(128, 0, 128);
    private final static Color INDIGO = new Color(75, 0, 130);
    
    //a utilizar no arco-iris iniciando da parte mais interna
    //as duas entradas em branco resultam em um arco vazio no centro
    private Color[] colors = {Color.WHITE, Color.WHITE, VIOLET, INDIGO, Color.BLUE,
    Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED};
    
    //construtor
    public ClasseDesenharArcoIris(){
        setBackground( Color.WHITE);//configura oo fundo como branco
    }
    
    //desenha o arco-iris utilizando arcos concêntricos
    public void paintComponent( Graphics g){
        super.paintComponent(g);
        int radius = 20; //raios de um arco
        
        //desenha o arco-íris perto da parte central inferior
        int centerX = getWidth()/2;
        int centerY = getWidth()-10;
        
        //desenha arcos preenchidos com o mais externo
        for(int counter = colors.length; counter > 0; counter--){
            //configura a cor para o arco atual
            g.setColor( colors[ counter -1] );
            
            //configura o arco de 0 a 180 graus
            g.fillArc(centerX - counter * radius, centerY - counter * radius, counter * radius * 2, counter * radius *2,
                    0, 180);
        }
    }
}

Classe principal

package arcoiris;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class ClasseDesenharArcoIris extends JPanel{
    //define as cores indigo e violeta
    private final static Color VIOLET = new Color(128, 0, 128);
    private final static Color INDIGO = new Color(75, 0, 130);
    
    //a utilizar no arco-iris iniciando da parte mais interna
    //as duas entradas em branco resultam em um arco vazio no centro
    private Color[] colors = {Color.WHITE, Color.WHITE, VIOLET, INDIGO, Color.BLUE,
    Color.GREEN, Color.YELLOW, Color.ORANGE, Color.RED};
    
    //construtor
    public ClasseDesenharArcoIris(){
        setBackground( Color.WHITE);//configura oo fundo como branco
    }
    
    //desenha o arco-iris utilizando arcos concêntricos
    public void paintComponent( Graphics g){
        super.paintComponent(g);
        int radius = 20; //raios de um arco
        
        //desenha o arco-íris perto da parte central inferior
        int centerX = getWidth()/2;
        int centerY = getWidth()-10;
        
        //desenha arcos preenchidos com o mais externo
        for(int counter = colors.length; counter > 0; counter--){
            //configura a cor para o arco atual
            g.setColor( colors[ counter -1] );
            
            //configura o arco de 0 a 180 graus
            g.fillArc(centerX - counter * radius, centerY - counter * radius, counter * radius * 2, counter * radius *2,
                    0, 180);
        }
    }
}

JavaFX

EXEMPLO 1: Botão de painel

package paineis;

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

/**
 *
 * @author HENRIQUE
 */
public class BotaoPainel extends Application{
    StackPane painel = new StackPane();

    @Override
    public void start(Stage stage) throws Exception {
        painel.getChildren().add(new Button("Clique aqui"));
        
        Scene scene = new Scene(painel, 200, 50);
        stage.setTitle("Botão dentro de um painel");
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}

EXEMPLO 2: Circulo
package paineis;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author HENRIQUE
 */
public class Circulo extends Application{
    @Override
    public void start(Stage stage){
        Circle circle = new Circle();
        circle.setCenterX(100);//cpordenada
        circle.setCenterY(100);//coordenada
        circle.setRadius(50);
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.WHITE);
        
        Pane pane = new Pane();
        pane.getChildren().add(circle);
        
        Scene scene = new Scene(pane, 200, 200);
        stage.setTitle("Exibindo um circulo");
        stage.setScene(scene);
        stage.show();
        
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}

EXEMPLO 3: Circulo centralizado

package paineis;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
 *
 * @author HENRIQUE
 */
public class CirculoCentralizado extends Application{
    @Override
    
    public void start(Stage stage){
        Pane pane = new Pane();
        
        Circle circle = new Circle();
        circle.centerXProperty().bind(pane.widthProperty().divide(2));
        circle.centerYProperty().bind(pane.heightProperty().divide(2));
        circle.setRadius(50);
        circle.setStroke(Color.BLACK);
        circle.setFill(Color.WHITE);
        //circle.setFill(Color.RED);
        pane.getChildren().add(circle);
        
        Scene scene = new Scene(pane, 200, 200);
        stage.setTitle("Circulo Sempre Centralizado");
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}

EXEMPLO 4: Interface com JavaFX

package paineis;

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 HENRIQUE
 */
public class MinhaPrimeiraInterface extends Application {
    @Override
    public void start (Stage primaryStage){
        Button btn = new Button("Sou um Botão");
        Scene scene = new Scene(btn, 200, 250);
        primaryStage.setTitle("Minha Primeira Interface JavaFX");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        Stage stage = new Stage();
        stage.setTitle("Nova janela");
        stage.setScene(new Scene(new Button("Mais um botão"),100, 100));
        stage.show();
    }
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}


EXEMPLO 5: Interface dentro de uma interface

package paineis;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

/**
 *
 * @author HENRIQUE
 */
public class PainelDentroDePainel extends Application{

    @Override
    public void start(Stage stage) {
        BorderPane painelPrincipal = new BorderPane();
        FlowPane painelSul = new FlowPane();
        
        painelSul.getChildren().add(new Button("Botão 1"));
        painelSul.getChildren().add(new Button("Botão 2"));
        painelPrincipal.setBottom(painelSul);
        
        Scene scene = new Scene(painelPrincipal, 400, 400);
        stage.setTitle("Painel dentro de um Painel");
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {
        Application.launch(args);
    }
}





04/05/2020

Relógio analógico em java



Classe Clock
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package relogioAnalogico;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javafx.application.Application;

import javafx.application.Platform;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;

/**
 *
 * @author HENRIQUE
 */
public class Clock extends Pane implements Runnable {
  private int hour;
  private int minute;
  private int second;
  // Largura e altura do painel do relógio
  private double w = 250, h = 250;
  /** Cria o relógio com a hora atual do sistema */
  public Clock() {
    setCurrentTime();
    Thread t = new Thread(this);
    t.setDaemon(true);
    t.start();
  }
  /** Cria o relógio com o horário especificado nos parâmetros */
  public Clock(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
    paintClock();
  }
  public int getHour() {
    return hour;
  }
  public void setHour(int hour) {
    this.hour = hour;
    paintClock();
  }
  public int getMinute() {
    return minute;
  }
  public void setMinute(int minute) {
    this.minute = minute;
    paintClock();
  }
  public int getSecond() {
    return second;
  }
  public void setSecond(int second) {
    this.second = second;
    paintClock();
  }
  public double getW() {
    return w;
  }
  public void setW(double w) {
    this.w = w;
    paintClock();
  }
  public double getH() {
    return h;
  }
  public void setH(double h) {
    this.h = h;
    paintClock();
  }
  /* Set the current time for the clock */
  public void setCurrentTime() {
    // Cria um calendar com a hora atual do sistema
    Calendar calendar = new GregorianCalendar();
    // Set current hour, minute and second
    this.hour = calendar.get(Calendar.HOUR_OF_DAY);
    this.minute = calendar.get(Calendar.MINUTE);
    this.second = calendar.get(Calendar.SECOND);
    paintClock(); // Atualiza o gráfico do relógio
  }
  /** Desenha o relógio */
  private void paintClock() {
    // Inicializa os parâmetros gráficos do relógio
    //proporção da dimensão do relógio
    double clockRadius = Math.min(w, h) * 0.8 * 0.5;//80% do painel e 20% afastado do relogio
    
    double centerX = w / 2;
    double centerY = h / 2;
    // Desenha o círculo
    Circle circle = new Circle(centerX, centerY, clockRadius);
    circle.setFill(Color.WHITE);
    circle.setStroke(Color.BLACK);
    
    //posicionamentos
    Text t1 = new Text(centerX - 5, centerY - clockRadius + 12, "12");//decrementando o tamanho do raio para ficar no centro
    Text t2 = new Text(centerX - clockRadius + 3, centerY + 5, "9");
    Text t3 = new Text(centerX + clockRadius - 10, centerY + 3, "3");
    Text t4 = new Text(centerX - 3, centerY + clockRadius - 3, "6");
    
    Text t5 = new Text(centerX - clockRadius + 9, centerY + 5, "7");
    
    // Desenha o ponteiro do segundo
    double sLength = clockRadius * 0.8;
    double secondX = centerX + sLength * 
    Math.sin(second * (2 * Math.PI / 60));
    double secondY = centerY - sLength * 
    Math.cos(second * (2 * Math.PI / 60));
    Line sLine = new Line(centerX, centerY, secondX, secondY);
    sLine.setStroke(Color.RED);
    /*
     * Outra possibilidade é utilizar a classe Rotate. Você set o ponteiro para o meio dia (12:00) e
     * rotaciona de acordo com a respectiva hora/minuto/segundo 
     * sLine.getTransforms().add(new Rotate(360/60 * second,centerX,centerY));
     */
    
    // Desenha o ponteiro do minuto
    double mLength = clockRadius * 0.65;
    double xMinute = centerX + mLength * 
    Math.sin(minute * (2 * Math.PI / 60));//comprimento do arco
    double minuteY = centerY - mLength * 
    Math.cos(minute * (2 * Math.PI / 60));
    Line mLine = new Line(centerX, centerY, xMinute, minuteY);
    mLine.setStroke(Color.BLUE);//linha do segundo
    
      System.out.println(hour+":"+minute+":"+second);
    
    // Desenha o ponteiro da hora
    double hLength = clockRadius * 0.5;
    double hourX = centerX + hLength * 
    Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
    double hourY = centerY - hLength *
    Math.cos((hour % 12 + hour / 60.0) * (2 * Math.PI / 12));
    Line hLine = new Line(centerX, centerY, hourX, hourY);
    hLine.setStroke(Color.GREEN);
    getChildren().clear();  
    
    getChildren().addAll(circle, t1, t2, t3, t4, t5,sLine, mLine, hLine);
  }
  @Override
  public void run() {
    while (true) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Platform.runLater(new Runnable() {//classe do FX//passando na classe para gerenciar
        @Override
        public void run() {
          setCurrentTime();  
        }
      });
    }    
  }

Classe ClockTest

package relogioAnalogico;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author HENRIQUE
 */
public class ClockTest extends Application{
    Clock clock = new Clock();
    
    @Override
    public void start(Stage stage) throws Exception{
        Scene scene = new Scene(clock, 250, 250);
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}


Palavras chave:

ജാവയിലെ അനലോഗ് ക്ലോക്ക്
Аналоговий годинник у Java
Saacadda analog ee java
Analog klocka i java
នាឡិកាអាណាឡូកនៅចាវ៉ា
Analog jam ing jawa
Жава дахь аналог цаг
जाभामा एनालग घडी
Analoge klok yn java
Analóg óra java-ban
שעון אנלוגי בג'אווה
जावा में एनालॉग घड़ी
Đồng hồ analog trong java

Layout em Java

EXEMPLO 1:

package visao;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutStackPane extends Application{
    @Override
    public void start(Stage primary){
        StackPane stackPane = new StackPane();
        stackPane.setPadding(new Insets(20));
        Rectangle r1 = new Rectangle(300, 300);
        r1.setFill(Color.RED);
        Rectangle r2 = new Rectangle(200, 200);
        r2.setFill(Color.BLUE);
        Rectangle r3 = new Rectangle(100, 100);
        r3.setFill(Color.AQUA);
        Rectangle r4 = new Rectangle(50, 50);
        r4.setFill(Color.BROWN);
        stackPane.getChildren().addAll(r1, r2, r3, r4);
        
        Scene cena = new Scene(stackPane);
        primary.setScene(cena);
        primary.setTitle("Gerenciador de Layout StackPane");
        primary.show();
    }
    public static void main(String[] args) {
        LayoutStackPane.launch(args);
    }
    
}



EXEMPLO 2:

package visao;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutVBox extends Application{
    @Override
    public void start(Stage primaryStage) throws Exception{
        
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(20));
        Rectangle r1 = new Rectangle(50, 50);
        Rectangle r2 = new Rectangle(100, 100);
        Rectangle r3 = new Rectangle(25, 100);
        Rectangle r4 = new Rectangle(250, 50);
        VBox.setMargin(r1, new Insets(10, 10, 10, 10));
        vbox.getChildren().addAll(r1, r2, r3, r4);

        Scene cena = new Scene(vbox);
        primaryStage.setScene(cena);
        primaryStage.setTitle("Gerenciador de Layout VBox");
        primaryStage.show();
    }
    
    public static void main(String[] args) {
        LayoutVBox.launch(args);
    }   
}

EXEMPLO 3:

package visao;
import javafx.geometry.Insets;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutHBox extends Application{
    @Override
    public void start(Stage Henrique){
        HBox hbox = new HBox(15);
        hbox.setPadding(new Insets(20));
        Rectangle r1 = new Rectangle(100, 100);
        Rectangle r2 = new Rectangle(200, 200);
        Rectangle r3 = new Rectangle(50, 200);
        Rectangle r4 = new Rectangle(200, 50);
        HBox.setMargin(r1, new Insets(10, 10, 10, 10));
        hbox.getChildren().addAll(r1, r2, r3, r4);
        
        Scene cena = new Scene(hbox);
        Henrique.setScene(cena);
        Henrique.setTitle("Gerenciador de Layout HBox");
        Henrique.show();
    }
    
    public static void main(String[] args) {
        LayoutHBox.launch(args);
    }
}


EXEMPLO 4:

package visao;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutFlowPane extends Application{
    @Override
    public void start(Stage primaryKey){
        FlowPane flowPane = new FlowPane(Orientation.VERTICAL);//fluxo de distribuição
        flowPane.setAlignment(Pos.TOP_LEFT);
        flowPane.setPadding(new Insets(20));
        Rectangle r1 = new Rectangle(50, 50);//quadrado 1
        r1.setFill(Color.RED);
        Rectangle r2 = new Rectangle(150, 60);//retangulo vertical
        r2.setFill(Color.BLUE);
        Rectangle r3 = new Rectangle(250, 50);
        r3.setFill(Color.AQUA);
        Rectangle r4 = new Rectangle(250, 50);
        FlowPane.setMargin(r1, new Insets(10, 10, 10, 10));
        flowPane.getChildren().addAll(r1, r2, r3, r4);
        
        Scene cena = new Scene(flowPane);
        primaryKey.setScene(cena);
        primaryKey.setTitle("Gerenciador de Layout FlowPane");
        primaryKey.show();
    }
    public static void main(String[] args) {
        LayoutFlowPane.launch(args);
    }
}

Vetor em JavaScript

const filhas = ['Aline','Gabriela','Amanda']
const filhos = ['Israel','Juliana','Mariana']
const todos = filhas.concat(filhos)
console.log(todosfilhasfilhos)

console.log([].concat([1,2],[3,4],5, [[6,7]]))


03/05/2020

HTML - Caixa de diálogo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ex03</title>
</head>
<body>
    <script>
        var n1 = Number.parseFloat(window.prompt('Digite um número: '))//convertendo para float
        var n2 = Number.parseInt(window.prompt('Digite o segundo número'))//convertendo para inteiro
        var s = n1 + n2
        //window.alert('A soma é = '+s);//concatenação
        //window.alert("A SOMA 2 = "+String(s))//converte para uma string
        window.alert(`A soma de ${n1} e ${n2} = ${s}`);
    </script>
</body>
</html>




Métodos com array em JavaScript

const pilotos = ['Victor', 'Afonso', 'Henrique','Aline Queiroz','Juliana Ristow']
console.log(pilotos)//exibindo o array

pilotos.pop()//Juliana Ristow foi desempilhado
console.log(pilotos)

pilotos.push('IELSON')//empilha IELSON
console.log(pilotos)

pilotos.shift()//remove o primeiro elemento
console.log(pilotos)

// splice pode adicionar e remover elementos

pilotos.splice(3, 0,'TINA', 'EVELYN')//adiciona na coluna 3 linha 1 tina e evelyunb
console.log(pilotos)

const algunsNomes = pilotos.splice(2)//novo array adiciona todos a partir da coluna 2
console.log(algunsNomes)

const outrosNomes = algunsNomes.splice(2,3)//adiciona a partir da coluna 2 de 'algunsNomes', no maximao 3 elmentos
console.log(outrosNomes)




Função no JavaScript

function parimpar(n){
    if(n %2 == 0){
        return "É par !"
    }else{
        return "Ímpar"
    }
}

function soma(n1 = 0, n2 = 0){
    return n1 + n2
}

function fatorial(num){
    let fat = 1
    for(let c = num; c > 1; c--){
        fat *= c
    }
    return fat
}

console.log(parimpar(78))
console.log("Soma = ",soma(10, 5))
console.log("Fatorial = ",fatorial(15))


01/05/2020

PROCV no Microsoft Excel

Utilizando a função PROCV no Excel
Exemplo 1:

Fórmula:

=PROCV(A6; A1:B4; 2;0)    ou    =PROCV(A6; A1:B4; 2;1)

Resultado: Campinas, Maria

Exemplo 2:

Fórmula aplicada na coluna B "RETORNO"

=PROCV(A2;E2:G8;2;1)

Fórmula aplicada na coluna C "RETORNO DA IDADE"

=PROCV(A2;E2:G8;3;0)

Obs: os indicadores em vermelho indicam que a procura por ser vertical, ela irá procurar a última ocorrência da célula vertical caso o valor não esteja cadastrado

Vetor em JavaScript

let num = [5,8,2,9,3]

console.log("Vetor = ",num)

num[3] = 6

console.log("Novo valor na posição [3]",num)

num.push(7)//insere o valor 7 na última posição
console.log("Novo vetor = ",num)

console.log("Tamanho = ",num.length)
num.sort()
console.log("ORDENADO = ",num)
console.log("Posição 2 = ",num[2])

for(let i = 0; i < num.length; i++){
    console.log(i," ",num[i])
}

console.log("Método 2")

for(let j in num){//só funciona para arrays e objetos
    console.log(j," -> ",num[j])
}

console.log(num.indexOf(7))//vai buscar onde tem o valor 7 e retorna a posição
if (num.indexOf(150) == -1) {
    console.log("pOSIÇÃO NÃO ENCONTRADA !")
}else{
    console.log(num.indexOf(150))
}