domingo, 2 de abril de 2017

Javafx - imprimir e pesquisar inteiros em array

Vamos imprimir um array numa janela gráfica
com o uso da biblioteca javafx, quem testar
este código ficará surpreso com a beleza
da interface, onde temos um textfield,
menu e botões bem organizado.
O programa  é indicado a quem
já possui bons conhecimentos de java.

Veja abaixo imagens do programa em execução:








Veja abaixo o código do programa:




import java.util.Arrays;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.scene.Node;
import javafx.geometry.Insets;
import javafx.scene.layout.HBox;
import java.util.function.UnaryOperator;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
////////////////////////////////////////////////////////////////////////////////
public class PROJETO extends Application {
     static Stage stage;
     static String str = "";
     static String str_1 = "MUITO OBRIGADO";
     static String str_3 = "Por: Samuel Lima";
     static String str_2 = "";
     static String str_4 = "";
     static int a = 0, b = 0, c = 0, d = 0, i, n = 100, y = 0;
     static int vet [ ] = new int [ n ];
     static Button btn_2 = new Button ( "cls" );
     static TextField textField = new TextField ( );
     static HBox hbox = new HBox ( textField );
     static BorderPane borderPane = new BorderPane ( );
     static Canvas canvas = new Canvas ( 690, 390 );
     static GraphicsContext ctx = canvas.getGraphicsContext2D ( );
     static Pane root = new Pane ( );
     static Scene scene = new Scene ( root, 660, 340 );
     static MenuBar menuBar = new MenuBar ( );
     // ////////////////////////////////////////////////////////////////////////
     // Chamando uma função depois de um certo tempo
     public static void Tempo_3 ( ) {
         ctx.setFill ( Color.RED );
         ctx.fillText ( str_1, 280, 320 );
     }
     public static void Tempo_2 ( ) {
         ctx.setFill ( Color.BLUE );
         ctx.fillText ( str_3, 280, 300 );
     }
     public static void Tempo_1 ( ) {
         // Coluna, linha, comprimento, altura
         // Apagando uma linha ou partes
         ctx.clearRect ( 150, 330, 300, 60 );
     }
     // ////////////////////////////////////////////////////////////////////////
     public static int Sleep ( int x, int k ) {
         Task < Integer > close = new Task < Integer > ( ) {
              @Override
              protected Integer call ( ) throws Exception {
                   Thread.sleep ( x );
                   return null;
              }
         };
         close.setOnSucceeded ( c -> {
              if ( k == 1 )
                   Tempo_1 ( );
              if ( k == 2 )
                   Tempo_2 ( );
              if ( k == 3 )
                   Tempo_3 ( );
         } );
         new Thread ( close ).start ( );
         return 0;
     }
     // ////////////////////////////////////////////////////////////////////////
     public static Node But_ton_2 ( ) {
         Button btn_2 = new Button ( "cls" );
         btn_2.setPrefWidth ( 50 );// Largura do botão
         btn_2.setLayoutX ( 21 );// Posição do botão
         btn_2.setPrefHeight ( 20 );// altura do botão
         btn_2.setLayoutY ( 305 );// //Posição do botão
         btn_2.setOnAction ( new EventHandler < ActionEvent > ( ) {
              @Override
              public void handle ( ActionEvent event ) {
                   // Coluna, linha, comprimento, altura
                   // Apagando uma linha ou partes
                   ctx.clearRect ( 150, 270, 400, 60 );
                   textField.clear ( );
              }
         } );
         root.getChildren ( ).add ( btn_2 );
         return btn_2;
     }
     // ////////////////////////////////////////////////////////////////////////
     public static void Line ( ) {
         for ( i = 1; i <= n; i++ ) {
              vet [ a ] = i;
              a++;
         }
         for ( i = 0; i < n; i++ ) {
              if ( i == 20 )
                   str += ( "\n" );
              if ( i == 40 )
                   str += ( "\n" );
              if ( i == 60 )
                   str += ( "\n" );
              if ( i == 80 )
                   str += ( "\n" );
              if ( i >= 20 && i <= 100 ) {
                   str += ( "  " );
                   str = str + vet [ i ];
              }
              if ( i >= 0 && i <= 19 ) {
                   str += ( "   " );
                   str = str + vet [ i ];
              }
         }
         ctx.setFill ( Color.BLACK );
         ctx.fillText ( str, 70, 110 );
     }
     // ////////////////////////////////////////////////////////////////////////
     public static int Menu_Bar ( ) {
         EventHandler < ActionEvent > action = changeTabPlacement ( );
         Menu menu = new Menu ( "Arq" );
         MenuItem top = new MenuItem ( "Exit" );
         top.setOnAction ( action );
         menu.getItems ( ).add ( top );
         MenuItem bottom = new MenuItem ( "Inf" );
         bottom.setOnAction ( action );
         menu.getItems ( ).add ( bottom );
         menuBar.getMenus ( ).add ( menu );
         root.prefHeightProperty ( ).bind ( scene.heightProperty ( ) );
         root.prefWidthProperty ( ).bind ( scene.widthProperty ( ) );
         borderPane.setTop ( menuBar );
         return 0;
     }
     // ////////////////////////////////////////////////////////////////////////
     private static EventHandler < ActionEvent > changeTabPlacement ( ) {
         return new EventHandler < ActionEvent > ( ) {
              public void handle ( ActionEvent event ) {
                   MenuItem mItem = ( MenuItem ) event.getSource ( );
                   String side = mItem.getText ( );
                   int b = 0;
                   if ( "Exit".equalsIgnoreCase ( side ) ) {
                        System.exit ( 0 );
                   } else if ( "Inf".equalsIgnoreCase ( side ) ) {
                        textField.clear ( );
                        But_ton_2 ( );
                        b = 3;
                        Sleep ( 2800, b );
                        b = 2;
                        Sleep ( 1800, b );
                        b = 4;
                        Sleep ( 1800, b );
                   }
              }
         };
     }
     // ////////////////////////////////////////////////////////////////////////
     public static void limitTextField ( TextField textField, int limit ) {
         UnaryOperator < Change > textLimitFilter = change -> {
              if ( change.isContentChange ( ) ) {
                   int newLength = change.getControlNewText ( ).length ( );
                   if ( newLength > limit ) {
                        String trimmedText = change.getControlNewText ( )
                                 .substring ( 0, limit );
                        change.setText ( trimmedText );
                        int oldLength = change.getControlText ( ).length ( );
                        change.setRange ( 0, oldLength );
                   }
              }
              return change;
         };
         textField.setTextFormatter ( new TextFormatter < Object > (
                   textLimitFilter ) );
     }
     // ////////////////////////////////////////////////////////////////////////
     private static int Bind ( ) {
         textField.setOnKeyPressed ( new EventHandler < KeyEvent > ( ) {
              @Override
              public void handle ( KeyEvent event ) {
                   //Limita o total de caracteres do textfield
                   limitTextField ( textField, 3 );
                   // textField.setPrefColumnCount ( 3 );
                   if ( event.getCode ( ) == KeyCode.ENTER ) {
                        ctx.setFont ( Font.font ( "Arial", FontWeight.NORMAL, 13 ) );
                        ctx.setFill ( Color.BLUE );
                        y = textField.getText ( ).length ( );
                        // convertendo string para inteiro
                        int r = Integer.parseInt ( textField.getText ( ) );
                        if ( Integer.parseInt ( textField.getText ( ) ) > 0
                                 && Integer.parseInt ( textField.getText ( ) ) < 101 ) {
                            int index = Arrays.binarySearch ( vet, r );
                            System.out.printf("\n%d", index );
                            str_4 += "ª";
                            if ( y == 3 ) {
                                a = 275;
                                b = 415;
                                c = 430;
                                d = 390;
                            }
                            if ( y == 2 ) {
                                a = 260;
                                b = 385;
                                c = 400;
                                d = 370;
                            }
                            if ( y == 1 ) {
                                a = 260;
                                b = 380;
                                c = 395;
                                d = 370;
                            }
                            String st = Integer.toString ( index + 1 );
                            ctx.fillText ( "O número", 175, 280 );
                            ctx.setFill ( Color.RED );
                            ctx.fillText ( st, 240, 280 );
                            ctx.setFill ( Color.BLUE );
                            ctx.fillText ( "Foi encontrado na", a, 280 );
                            ctx.setFill ( Color.RED );
                            ctx.fillText ( str_4, b, 285 );
                            String s_t = Integer.toString ( index + 1);
                            ctx.setFill ( Color.RED );
                            ctx.fillText ( s_t, d, 280 );
                            ctx.setFill ( Color.BLUE );
                            ctx.fillText ( "posição do array", c, 280 );
                            But_ton_2 ( );
                        }
                   }
                   str_4 = "";
              }
         } );
         return 0;
     }
     // ////////////////////////////////////////////////////////////////////////
     @Override
     public void start ( Stage stage ) {
         ctx.setLineWidth ( 18.0 );
         ctx.setStroke ( Color.BLUE );
         ctx.strokeRoundRect ( 10, 10, 650, 330, 20, 0 );
         stage.setTitle ( "ARRAY: IMPRIMIR E PESQUISAR II" );
         stage.setScene ( scene );
         stage.setResizable ( false );
         Menu_Bar ( );
         ctx.setFill ( Color.RED );
         ctx.setFont ( Font.font ( "Serif", FontWeight.BOLD, 20 ) );
         ctx.fillText ( "ARRAY: IMPRIMIR E PESQUISAR II", 150, 50 );
         ctx.setFont ( Font.font ( "Arial", FontWeight.NORMAL, 15 ) );
         ctx.setFill ( Color.BLUE );
         ctx.fillText ( "IMPRIMINDO O ARRAY ABAIXO", 220, 80 );
         Line ( );
         textField.setPrefColumnCount ( 2 );
         Bind ( );
         root.getChildren ( ).add ( canvas );
         hbox.setPadding ( new Insets ( 220, 0, 10, 100 ) );
         ctx.setFont ( Font.font ( "Tahoma", FontWeight.NORMAL, 12 ) );
         ctx.setFill ( Color.RED );
         ctx.fillText ( "Digite um número para pesquisar", 100, 210 );
         ctx.setFill ( Color.BLUE );
         ctx.fillText ( "Enter", 150, 240 );
         root.getChildren ( ).add ( hbox );
         borderPane.setPadding ( new Insets ( 19, 0, 10, 19 ) );
         root.getChildren ( ).addAll ( borderPane );
         stage.show ( );
     }
     // ////////////////////////////////////////////////////////////////////////
     public static void main ( String [ ] args ) {
         Application.launch ( args );
     }
}

Nenhum comentário:

Postar um comentário

Observação: somente um membro deste blog pode postar um comentário.