Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
11 kB
2
Indexable
Never
package cs1302.gallery;

import javafx.animation.Animation.Status;
import javafx.animation.Animation;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
import java.util.Arrays;
import javafx.util.Duration;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import com.google.gson.*;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.Priority;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.scene.control.Label;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.TilePane;
import javafx.scene.control.ProgressBar;
import java.lang.Thread;
import java.lang.Runnable;
import javafx.scene.control.Separator;
import javafx.geometry.Orientation;
import java.net.URLEncoder;
import java.net.URL;
import java.io.InputStreamReader;
import javafx.application.Platform;
import java.util.Random;

/**
 * Represents an iTunes GalleryApp.
 */
public class GalleryApp extends Application {

    VBox vBox;
    VBox aboutMe;
    ToolBar pane;
    ToolBar toolBarBox;

    MenuBar menuBar;
    Menu fileMenu;
    Menu helpMenu;
    MenuItem aboutMeMenu;
    MenuItem exitMenu;

    Button pauseButton;
    Separator separator;
    Button updateButton;
    TextField urlField;

    TilePane tilePane;
    ImageLoader[] imageLoaders;
    String[] extras;

    ProgressBar progressBar;
    Timeline timeline;
    String neededUrl;
    double percent;

    Alert errorAlert;
    /**
     * The itunes url at the front.
     */
    private final String itunesFront =
        "https://itunes.apple.com/search?term=";

    /**
     * The itunes url at the end.
     */
    private final String itunesBack =
        "&limit=50&media=music";

    /**
     * Start method.
     */
    @Override
    public void start(Stage stage) {
        vBox = new VBox(8);

        menuBar();
        toolBar();
        defaultImagePane();
        progressBar();

        updateImageButton();
        generateRandomImage();
        updateImage(urlField.getText());
        timeline.pause();
        pauseImage();

        Scene scene = new Scene(vBox);
        stage.setMaxWidth(1280);
        stage.setMaxHeight(720);
        stage.setTitle("GalleryApp!");
        stage.setScene(scene);
        stage.sizeToScene();
        stage.show();
    } // start

    /**
     * Creates a menuBar item.
     */
    public void menuBar() {
        //pane = new ToolBar();

        menuBar = new MenuBar();
        fileMenu = new Menu("File");
        helpMenu = new Menu("Help");

        aboutMeMenu = new MenuItem("About");
        EventHandler<ActionEvent> aboutMeEvent = event -> {
            Alert aboutAlert = new Alert(AlertType.INFORMATION);
            aboutAlert.setResizable(true);
            aboutAlert.setTitle("About Luan Ho");
            aboutAlert.setHeaderText(null);
            Image luanImage = new Image("file:resources/luanPicture.jpg", 450, 450, false, false);
            ImageView luanView = new ImageView(luanImage);
            luanView.setFitHeight(450);
            luanView.setFitHeight(450);
            aboutAlert.setGraphic(luanView);
            aboutAlert.setContentText("Luan Ho\nlqh24430@uga.edu\nVersion 10.1");
            aboutAlert.showAndWait();
        };
        aboutMeMenu.setOnAction(aboutMeEvent);

        exitMenu = new MenuItem("Exit");

        EventHandler<ActionEvent> exit = event -> {
            Runnable instructions = () -> {
                System.exit(0);
            };
            runNow(instructions);
        };
        exitMenu.setOnAction(exit);

        fileMenu.getItems().add(exitMenu);
        helpMenu.getItems().add(aboutMeMenu);
        menuBar.getMenus().addAll(fileMenu, helpMenu);

        vBox.getChildren().add(menuBar);
    } // menuBar

    /**
     * Creates the toolBar item.
     */
    public void toolBar() {
        toolBarBox = new ToolBar();

        pauseButton = new Button("Play");
        separator = new Separator(Orientation.VERTICAL);
        Label searchQuery = new Label("Search Query: ");
        urlField = new TextField("jack johnson");
        updateButton = new Button("Update Images");
        toolBarBox.getItems().addAll(pauseButton, separator, searchQuery, urlField, updateButton);

        vBox.getChildren().add(toolBarBox);

    } // toolBar

    /**
     * Sets images.
     *
     * @param url the url of the search
     * @param index the position
     */
    public void setImages(String url, int index) {
        imageLoaders[index].loadImage(url);
    }

    /**
     * This gives functioanlity to the update button.
     */
    public void updateImageButton() {
        EventHandler<ActionEvent> update = e -> {
            Runnable instructions = () -> {
                neededUrl = urlField.getText();
                timeline.pause();
                updateImage(neededUrl);
            };
            runNow(instructions);
        };
        updateButton.setOnAction(update);

    }

    /**
     * Update the images in the search query.
     * Used in toolBar.
     *
     * @param s the string url.
     */
    public void updateImage(String s) {
        try {
            updateButton.setDisable(true);
            String sURL = URLEncoder.encode(s.toLowerCase(), "UTF-8");
            String itunesURL = itunesFront + sURL + itunesBack;
            URL url = new URL(itunesURL);
            InputStreamReader reader = new InputStreamReader(url.openStream());
            JsonElement je = JsonParser.parseReader(reader);
            JsonObject root = je.getAsJsonObject();
            JsonArray results = root.getAsJsonArray("results");
            int numResults = results.size();
            Platform.runLater(() -> progressBar.setProgress(0));
            if (numResults > 20) {
                extras = new String[numResults - 20];
                for (int i = 0; i < 20; i++) {
                    JsonObject result = results.get(i).getAsJsonObject();
                    JsonElement artworkUrl100 = result.get("artworkUrl100");
                    if (artworkUrl100 != null) {
                        setImages(artworkUrl100.getAsString(), i);
                        loadProgress(i);
                    }
                }
                Platform.runLater(() -> progressBar.setProgress(1));
                for (int i = 20; i < numResults; i++) {
                    JsonObject result = results.get(i).getAsJsonObject();
                    JsonElement artworkUrl100 = result.get("artworkUrl100");
                    if (artworkUrl100 != null) {
                        extras[i - 20] = artworkUrl100.getAsString();
                    }
                }
            } else {
                Runnable alert = () -> {
                    errorAlert = new Alert(AlertType.ERROR);
                    errorAlert.setResizable(true);
                    errorAlert.setTitle("Error!");
                    errorAlert.setHeaderText("Cannot find more than 21 images for this search.");
                    errorAlert.setContentText("Try another search.");
                    errorAlert.showAndWait();
                    Platform.runLater( () -> progressBar.setProgress(1));
                };
                Platform.runLater(alert);
            } //else
        } catch (UnsupportedEncodingException z) {
            System.out.println("The URL cannot be encoded");
        } catch (MalformedURLException mue) {
            System.out.println("The URL is malformed");
        } catch (IOException ioe) {
            System.out.println("IOException");
        } finally {
            timeline.play();
            Platform.runLater(() -> pauseButton.setText("Pause"));
            updateButton.setDisable(false);
        }
    }

    /**
     * This progresses the progress bar.
     * @param index the index.
     */
    public void loadProgress(final double index) {
        Runnable z = () -> {
            percent = (index / 20.0);
            progressBar.setProgress(percent);
        };
        Platform.runLater(z);
    }

    /**
     * Generate random images.
     */
    public void generateRandomImage() {
        EventHandler<ActionEvent> handler = event -> {
            Random random = new Random();
            imageLoaders[random.nextInt(20)].loadImage(extras[random.nextInt(extras.length)]);
        };
        KeyFrame keyFrame = new KeyFrame(new Duration(2000.0), handler);
        timeline = new Timeline(keyFrame);
        this.timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
    }

    /**
     * Pauses the images.
     */
    public void pauseImage() {
        EventHandler<ActionEvent> pausePlay = event -> {
            Runnable instructions = () -> {
                if (pauseButton.getText().equals("Pause")) {
                    Platform.runLater(() -> pauseButton.setText("Play"));
                    timeline.pause();
                } else {
                    Platform.runLater(() -> pauseButton.setText("Pause"));
                    timeline.play();
                }
            }; //Runnable
            runNow(instructions);
        }; //pausePlay
        pauseButton.setOnAction(pausePlay);

    }

    /**
     * Creates the image pane.
     */
    public void defaultImagePane() {
        tilePane = new TilePane();

        tilePane.setPrefColumns(5);
        tilePane.setPrefRows(4);
        imageLoaders = new ImageLoader[20];
        for (int i = 0; i < imageLoaders.length; i++) {
            imageLoaders[i] = new ImageLoader();
            tilePane.getChildren().add(imageLoaders[i]);
        }
        vBox.getChildren().add(tilePane);

        //updateImage(urlField.getText());

    }

    /**
     * Creates a progress bar.
     */
    public void progressBar() {
        progressBar = new ProgressBar();

        progressBar.setProgress(1.00);

        vBox.getChildren().add(progressBar);
    }

    /**
     * Runs an action on a new thread.
     * From previous exercise.
     * @param target the action to run
     */
    public static void runNow(Runnable target) {
        Thread t = new Thread(target);
        t.setDaemon(true);
        t.start();
    }


} // GalleryApp