JAVAFX – Mudar cor do stroke StackedAreaChart

Estou com o seguinte problema, tenho um StackedAreaChart no JavaFX e preciso que dependendo do valor da data a linha da XYChart.Series mude para outra cor.

Tentei varias soluções, entretanto ao mudar ele muda todas as linhas o que é um comportamento indesejado.

EXEMPLO :

inserir a descrição da imagem aqui

Alguém sabe se isso e possível ?

java – JavaFX – Click do botão não reconhecido quando tento mudar de Pane

Overview: A janela principal da minha aplicação, baseada em máquina de estados, está dividida em dois Panes, um em cima e outro em baixo.
O Pane de baixo contém um botão (Move) que permite avançar para o próximo estado, substituindo o próprio Pane inferior por outro enquanto que o Pane superior se mantém.
Neste Pane que se segue existem algumas funcionalidades, sendo que uma delas é voltar para o Pane e estado anterior.
No entanto, em vez de alterar novamente de Pane para o anterior, o click do botão (Next Turn) nem sequer é registado e é impossível mudar para o Pane/estado anteriores.

Imagens para contexto: imgur images

Listeners e PropertyChange do Pane com botão Move que altera com sucesso o Pane/estado.

private void createListeners() {
    this.moveBtn.setOnAction(event - > this.game.move());
    this.logBtn.setOnAction(event - > {
        try {
            Desktop.getDesktop().open(new File("log.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

@Override
public void propertyChange(PropertyChangeEvent evt) {
    if (this.game.getGame().getState() instanceof AwaitToMove) {

        setupLogButton();

        BackgroundImage myBI = new BackgroundImage(new Image("src/ui/GUI/Resources/move-2.jpg", 800, 800, false, true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, new BackgroundSize(1.0, 1.0, true, true, false, false));
        this.father.setBackground(new Background(myBI));

        this.father.getChildren().add(this);

    } else {
        this.father.getChildren().remove(this);
    }
}

}

Listeners e PropertyChange do Pane com botão Next Turn que não consegue voltar para Pane/estado anteriores.

private void createListeners() {
    // não chega a entrar em this.game.nextTurn()
    this.nextTurnBtn.setOnAction(event - > this.game.nextTurn()); 
    this.landBtn.setOnAction(event - > this.game.landOnPlanet());
}

@Override public void propertyChange(PropertyChangeEvent evt) {
    if (this.game.getGame().getState() instanceof AwaitAroundPlanet) {

        clearComponents();
        try {
            createComponents();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        fillView();

        BackgroundImage myBI = new BackgroundImage(new Image("src/ui/GUI/Resources/orbit.jpg", 800, 800, false, true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, new BackgroundSize(1.0, 1.0, true, true, false, false));
        this.father.setBackground(new Background(myBI));

        setupOrbitDisplay();
        setupSpottedResources();
        checkButtons();

        this.father.getChildren().add(this);

    } else {
        this.father.getChildren().remove(this);
    }
}

Peço desculpa se não me fiz entender ou se coloquei a pergunta de maneira errada. A dúvida não é muito simples e é um pouco difícil de transmitir. Desde já obrigado.

Problema con tableview javafx – Stack Overflow en español

Intento listar pero no sirve. El metodo donde “enlazo” los datos. en actualizar solo agarro el arraylist que tengo de productos y agrego los que concuerdan con inventario.add(producto). pero si me añade los datos en el observablelist, es como si no se sincronizara con la tabla

@FXML
private TableView<Producto> tablaProductos;

@FXML
private TableView<Producto> tablaCarrito;

@FXML
private TableColumn<Producto, String> columnaNombre1;

@FXML
private TableColumn<Producto, String> columnaNombre2;

@FXML
private TableColumn<Ciudad, String> columnaDepartamento1;

@FXML
private TableColumn<Ciudad, String> columnaDepartamento2;

@FXML
private TableColumn<Ciudad, String> columnaCiudad1;

@FXML
private TableColumn<Ciudad, String> columnaCiudad2;

private ObservableList<Producto> inventario = FXCollections.observableArrayList(),
        carrito = FXCollections.observableArrayList();

private ArrayList<Producto> carro = new ArrayList<Producto>();

@Override
public void initialize(URL location, ResourceBundle resources)
{
    columnaNombre1.setCellValueFactory(new PropertyValueFactory<>("nombre"));
    columnaDepartamento1.setCellValueFactory(new PropertyValueFactory<>("departamento"));
    columnaCiudad1.setCellValueFactory(new PropertyValueFactory<>("ciudad"));

    tablaProductos.setItems(inventario);

    columnaNombre2.setCellValueFactory(new PropertyValueFactory<>("Nombre"));
    columnaDepartamento2.setCellValueFactory(new PropertyValueFactory<>("Departamento"));
    columnaCiudad1.setCellValueFactory(new PropertyValueFactory<>("Ciudad"));

    tablaProductos.setItems(carrito);
}

Aqui la clase Producto, se supone que los nombres de las variables serian las propiedades el PropertyValueFactory. pero no me lista nada de nada

import javafx.beans.property.SimpleStringProperty;
import java

fx.beans.property.StringProperty;

public class Producto
{
    private final int id;
    private final StringProperty nombre, descripcion;
    private final Ciudad ciudad;
    private int cantidad;
    private final double precio;

    public Producto(int id, String nombre, String descripcion, double precio, Ciudad ciudad, int cantidad)
    {
        super();
        this.id = id;
        this.nombre = new SimpleStringProperty(nombre);
        this.descripcion = new SimpleStringProperty(descripcion);
        this.precio = precio;
        this.ciudad = ciudad;
        this.cantidad = cantidad;
    }

    public int getId()
    {
        return id;
    }

    public String getNombre()
    {
        return nombre.get();
    }

    public void setNombre(String nombre)
    {
        this.nombre.set(nombre);
    }

    public String getDescripcion()
    {
        return descripcion.get();
    }

    public void setDescripcion(String descripcion)
    {
        this.descripcion.set(descripcion);
    }

    public double getPrecio()
    {
        return precio;
    }

    public Ciudad getCiudad()
    {
        return ciudad;
    }

    public int getCantidad()
    {
        return cantidad;
    }

    public void setCantidad(int cantidad)
    {
        this.cantidad = cantidad;
    }

}

y por si algo el de ciudad, de igual modo ya eliminé las columnas que acceden a la ciudad y asi pero sigue sin listar ni el nombre del producto

public class Ciudad
{
private int id;
private StringProperty ciudad, dpto;

public Ciudad(int id, String ciudad, String departamento)
{
    super();
    this.id = id;
    this.ciudad = new SimpleStringProperty(ciudad);
    this.dpto = new SimpleStringProperty(departamento);
}

public int getId()
{
    return id;
}

public void setId(int id)
{
    this.id = id;
}

public String getCiudad()
{
    return ciudad.get();
}

public void setCiudad(String ciudad)
{
    this.ciudad.set(ciudad);
}

public String getDepartamento()
{
    return dpto.get();
}

public void setDepartamento(String departamento)
{
    this.dpto.set(departamento);
}

}

java – How do I connect my JavaFx Scene Builder application to the MySQL database?

I am doing an application in Java and I used Scene Builder to create the graphical user interface.

My application saves employees. The new buttons for editing and deleting do their job. However, you save the changes in an XML file. I want you to connect to a database and save those changes to that database by inserting, changing, or deleting people in the application (using hibernation).

Application interface

Next, I leave the interface controller code:

  package controlador.vista;

import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;

import controlador.MainApp;
import controlador.modelo.Persona;
import controlador.util.Fecha;

public class PersonaOverviewController {
    @FXML
    private TableView personTable;
    @FXML
    private TableColumn firstNameColumn;
    @FXML
    private TableColumn lastNameColumn;
    @FXML
    private Label firstNameLabel;
    @FXML
    private Label lastNameLabel;
    @FXML
    private Label hireDateLabel;
    @FXML
    private Label dniLabel;
    @FXML
    private Label diasLabel;
    @FXML
    private TextField buscar;

    // Reference to the main application.
    private MainApp mainApp;

    /**
     * The constructor.
     * The constructor is called before the initialize() method.
     */
    public PersonaOverviewController() {
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        // Initialize the person table with the two columns.
        firstNameColumn.setCellValueFactory(
                cellData -> cellData.getValue().firstNameProperty());
        lastNameColumn.setCellValueFactory(
                cellData -> cellData.getValue().lastNameProperty());

        // Clear person details.
        showPersonDetails(null);

        // Listen for selection changes and show the person details when changed.
        personTable.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> showPersonDetails(newValue));
    }

    /**
     * Is called by the main application to give a reference back to itself.
     *
     * @param mainApp
     */
    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;

        // Add observable list data to the table
        personTable.setItems(mainApp.getPersonData());
    }

    /**
     * Fills all text fields to show details about the person.
     * If the specified person is null, all text fields are cleared.
     *
     * @param persona the person or null
     */
    private void showPersonDetails(Persona persona) {
        if (persona != null) {
            // Fill the labels with info from the person object.
            firstNameLabel.setText(persona.getFirstName());
            lastNameLabel.setText(persona.getLastName());
            hireDateLabel.setText(Fecha.format(persona.getHireDate()));
            dniLabel.setText(persona.getDni());
            persona.diasVacaciones();
            diasLabel.setText(Double.toString(persona.getDias()));

        } else {
            // Person is null, remove all the text.
            firstNameLabel.setText("");
            lastNameLabel.setText("");
            hireDateLabel.setText("");
            dniLabel.setText("");
            diasLabel.setText("");
        }
    }


    /**
     * Called when the user clicks the new button. Opens a dialog to edit
     * details for a new person.
     */
    @FXML
    private void handleNewPerson() {
        Persona tempPerson = new Persona();
        boolean okClicked = mainApp.showPersonEditDialog(tempPerson);
        if (okClicked) {
            mainApp.getPersonData().add(tempPerson);
        }

    }

    /**
     * Called when the user clicks the edit button. Opens a dialog to edit
     * details for the selected person.
     */
    @FXML
    private void handleEditPerson() {

        Persona selectedPerson = personTable.getSelectionModel().getSelectedItem();
        if (selectedPerson != null) {
            boolean okClicked = mainApp.showPersonEditDialog(selectedPerson);
            if (okClicked) {
                showPersonDetails(selectedPerson);

            }

        } else {
            // Nothing selected.
            Alert alert = new Alert(AlertType.WARNING);
            alert.initOwner(mainApp.getPrimaryStage());
            alert.setTitle("Sin selección");
            alert.setHeaderText("Sin persona seleccionada");
            alert.setContentText("Por favor, selecciona una persona de la tabla.");

            alert.showAndWait();
        }

    }

    /**
     * Called when the user clicks on the delete button.
     */
    @FXML
    private void handleDeletePerson() {
        int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            personTable.getItems().remove(selectedIndex);

        } else {
            // Nothing selected.
            Alert alert = new Alert(AlertType.WARNING);
            alert.initOwner(mainApp.getPrimaryStage());
            alert.setTitle("Error de selecion");
            alert.setHeaderText("No se ha seleccionado ningun registro");
            alert.setContentText("Por favor, seleccione una persona de la tabla.");
            alert.showAndWait();
        }
    }
    @FXML
    private void handleGastarVacaciones() {
         Persona selectedPerson = personTable.getSelectionModel().getSelectedItem();
         if (selectedPerson != null) {
             boolean okClicked = mainApp.showPersonDiasDialog(selectedPerson);
             if (okClicked) {
                 showPersonDetails(selectedPerson);
             }

         } else {
             // Nothing selected.
             Alert alert = new Alert(AlertType.WARNING);
             alert.initOwner(mainApp.getPrimaryStage());
             alert.setTitle("Sin selección");
             alert.setHeaderText("Sin persona seleccionada");
             alert.setContentText("Por favor, selecciona una persona de la tabla.");

             alert.showAndWait();
         }
    }

    @FXML
    private void buscarDatos() {

        personTable.setItems(mainApp.getPersonData());

        FilteredList filteredData = new FilteredList<>(mainApp.getPersonData(), p -> true);

        buscar.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(person -> {
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                String filtroMinuscula = newValue.toLowerCase();

                if (person.getFirstName().toLowerCase().indexOf(filtroMinuscula) != -1){
                    return true;
                }else if (person.getLastName().toLowerCase().indexOf(filtroMinuscula) != -1){
                    return true;
                }else if (person.getDni().toLowerCase().indexOf(filtroMinuscula) != -1){
                    return true;
                }else
                    return false;
            });
        });

        SortedList sortedData = new SortedList<>(filteredData);

        sortedData.comparatorProperty().bind(personTable.comparatorProperty());

        personTable.setItems(sortedData);
    }

}

I understand that in the new edit and delete buttons, I have to implement this change to the database with a type code:

SessionFactory factory = HibernateUtils.getSessionFactory();
                Session session = factory.openSession();

                   session.getTransaction().begin();
                   session.delete();
                   session.getTransaction().commit();

I've managed to put some occurrences of Persona in the database, but I do it when I initialize the app so that it contains some content when it starts. However, I want the changes to be made again, edited and deleted to affect the database, but I don't give the key on how to do it, can someone help me?

Thank you so much! If necessary, I can post more code if it helps.

Java – Concentric Squares – Recursion JavaFX

{
private final int SIZE = 500;
private final int DIST = 20;

public void concentricSquares4colorFillRec(int xy, int c, Group g)
{
Rectangle rect;
if(xy>0)
{
rect = new Rectangle(xy, xy, SIZE - 2*xy, SIZE - 2*xy);
if (c%4 == 0)
rect.setFill(Color.HOTPINK);
else if (c%4 == 1)
rect.setFill(Color.TURQUOISE);
else if (c%4== 2)
rect.setFill(Color.VIOLET);
else
rect.setFill(Color.FUCHSIA);
g.getChildren().add(rect);
concentricSquares4colorFillRec(xy-DIST,c+1, g);
}
}

public void start(Stage stage) throws Exception
{
Group root = new Group();
concentricSquares4colorFillRec(SIZE/2, 0,root);

Scene scene = new Scene(root, SIZE, SIZE, Color.WHITE);
stage.setTitle("Shapes Recursively ");

}

}

Why doesn't this code work? Can anyone help fix it! Must be recursive for JAVAFX

java – JavaFx How do I list data from more than one table in a TableView?

Good night guys, all right?
I'm having problems using JavaFx and multiple tables in the database. However, the question is how do I do this join in a TableView.

My selection looks like this:
I put it in MySQL WorkBench and it works normally:

                PreparedStatement stmt = conexao_Banco_Dados.prepareStatement("select "
                + "cadastro_clientes.ID_CLIENTE, cadastro_clientes.NOME_CLIENTE,n"
                + "cadastro_clientes.CADASTRO_PESSOA_FISICA, estado.ID_ESTADO, "
                + "estado.SIGLA_ESTADO, cidade.IDn"
                + "from cadastro_clientesn"
                + "inner join enderecon"
                + "on cadastro_clientes.ENDERECO_CLIENTE_ID = endereco.ID_ENDERECOn"
                + "inner join cidaden"
                + "on endereco.CIDADE_ID = cidade.IDn"
                + "inner join estadon"
                + "on cidade.estado_id = estado.id_estado");

The problem is that only customer data is listed! of states that I didn't want to list!
My @FXML looks like this:

    @FXML
    public void colocando_TableView(){
    tclId_Clientes.setCellValueFactory(new PropertyValueFactory("id_Cliente"));
    tcl_Nome_Clientes.setCellValueFactory(new PropertyValueFactory("nome_Cliente"));
    tcl_CPF_Clientes.setCellValueFactory(new PropertyValueFactory("cadastro_Pessoa_Fisica"));
    tcl_Sigla.setCellValueFactory(new PropertyValueFactory("sigla_Estado"));
    try {
        tbv_Exibicao_Clientes.setItems(atualizar_Tabela());
    } catch (SQLException ex) {
        Logger.getLogger(FXML_Clientes_CadastroController.class.getName()).log(Level.SEVERE, null, ex);
    }    
}
@FXML
public ObservableList atualizar_Tabela() throws SQLException{
    Clientes_DAO ced = new Clientes_DAO();
    return FXCollections.observableArrayList(ced.pesquisar_Clientes());    
}

And the statements are as follows:

@FXML private TableView tbv_Exibicao_Clientes;    
@FXML private TableColumn tclId_Clientes;
@FXML private TableColumn tcl_Nome_Clientes;
@FXML private TableColumn tcl_CPF_Clientes;
@FXML private TableColumn tcl_Sigla;

Note: I've tried and still can't.

height – How can the row height of TableView JavaFX be limited?

Hey guys.
It is difficult for me to find out how to limit the row height in tableView in JavaFX. I need this information so that the following problem does not occur:

Does anyone know how to apply this limitation in SceneBuilder or CSS?

Insert picture description here

Maven, JavaFx, Jlink – Where are my classes in the created folder?

With the Javafx Maven plugin, I created a custom JRE with my application as follows:

        
          org.openjfx
          javafx-maven-plugin
          0.0.3
          
            ${maven.compiler.target}
            MyApp
            _start
            ${project.groupId}.${project.artifactId}.App
          
      

When I double-click on _start.bat in MyApp bin, my app starts. This is great and works if I copy the MyApp folder to another computer too.
However, I cannot find my classes or JAR files in the MyApp folder. The file (s) must be somewhere else, otherwise the app would not run. But where?

Sincerely yours,

Michael

java – Add a JavaFX user interface to an MVC based terminal card game

I wrote a version of Castle that was previously played through the terminal. I recently revised my code (found here) to use the MVC design pattern. After adding a GUI, I will add network functions. The game should be thought of as a local single game (human) against AI at the moment.

The game controller contains the gameState, gameView and then the business logic to run the game. The business logic is essentially just a loop that the players go through one at a time telling everyone to choose a move, apply the move to the status, and then tell the view that the status should be printed (on the atm terminal).

The game consists of 3 types of players:

  • An information set MCTS AI player
  • AI player who only plays a basic strategy to play the lowest possible card (s)
  • Human player

The AI ​​players have a controller that contains the player model and business logic, as well as the player view (but only for human players). The player model is a generic POJO that contains hand cards, castle cards, etc. The logic varies from player to player, but is all stored in the controller. The game controller calls playerController.getMove (), the player then chooses his move depending on his strategy / implementation and returns it to the gameController.

The & # 39; Move & # 39; objects are created by the playerController and returned to the gameController. They contain information such as the card played or, if it cannot be played, it is a pick-up move, etc. The move objects contain the logic of how the player and the company make decisions about how they change the game status.

  1. GameController calls player.getMove (gameState).
  2. PlayerController selects a train and returns it
  3. The game controller calls move.doMove (gameState).
  4. Next player until someone wins

My first question is, is it okay that the & # 39; moves & # 39; storage logic or is there a better way? They are the only components that MVC does not strictly follow.

Second, and more importantly, I can't imagine how the game works with JavaFX as a GUI. I have no experience with JavaFX and little experience with the user interface in general, but I am trying. I read that the controller / view can be a little confused. I tried to find videos and resources to give me a better understanding, but none seems to be in the right context – turn-based, animation-free (for now) card game. In my head I imagine the GUI, where the cards of the players are open and the cards of the opponent are hidden, but are displayed with their backs up. The game is waiting for the human to select and validate the card (s) to play. It will then be updated to show the move completed. In AI opponents, it waits for a move to be selected and is then updated on the screen. But where does it go and how does it interact? I think the GameController / View should show the game status that the player can see and interact with. Isn't playerView then necessary?

I think I'm struggling to get a picture of how the GUI works for the player all the time, and I don't care about typing them until it's their turn, and how this fits into the game loop I've created so far have.

TO EDIT:

I managed to use ListView to create a scene showing the cards of the players that were dealt to them. However, I can't figure out how to add my game loop to the code.

    boolean print = true;
    boolean gameOver = false;

    do {
        for (PlayerController player : players) {
            if (gameOver) {
                break;
            }
            boolean playersTurn = true;
            while (playersTurn) {

                CastleMove move = player.getMove(gameState);
                doMove(move);

                // If the player does not burn the pile then it is the next players turn
                if (!move.burnsPile()) {
                    playersTurn = false;
                }
                if (gameState.isGameOver()) {
                    gameOver = true;
                    break;
                }
            }
        }
    } while (!gameOver);

When I add the code to the start () method, the card window is never displayed because it has not yet been executed. Where are we going?

Java – How to Reset Snake in Javafx Game?

I am queuing in Javafx, I have completed my game and I am trying to insert a reset button in my game. When I click the reset button (ENTER) the game should be reset, but the array list that stores the rectangles that make up the queue is not reset. For my life, I can't figure out how it works. Any help is appreciated, thanks!

Code: https://pastebin.com/yiQi8DSU

Code:

package finalproject;



public class FinalProject extends Application {

Random rand = new Random();

Pane canvas;
Scene scene;
double points1() = {100, 100, 1200, 100, 1200, 900, 100, 900,};
Polygon poly1;
Text Score, HighScore, GameOver, Reset, Time;
Font font1, font2;
Rectangle SnakeBody, Food, EndScreen, SpeedBoost, ScoreMultiplier;
ArrayList Snakes;
int RIGHT = 0, UP = 1, LEFT = 2, DOWN = 3;
int facing = 0;
int rightSpeed = 0, upSpeed = 0, leftSpeed = 0, downSpeed = 0;
int SnakeSpeed = 4;
int score = 0;
int Multiplier = 0;
int Booster = 0;
int Score2 = 0;
//int timeCount = 2000;
// long second = 1000000000;

public void Objects() {

    facing = RIGHT;

    Food = new Rectangle(600, 600, 20, 20);
    Food.setStroke(Color.RED);
    Food.setFill(Color.RED);

    SpeedBoost = new Rectangle(4000, 4000, 20, 20);
    SpeedBoost.setStroke(Color.WHITE);
    SpeedBoost.setFill(Color.PURPLE);

    ScoreMultiplier = new Rectangle(4000, 4000, 15, 15);
    ScoreMultiplier.setStroke(Color.WHITE);
    ScoreMultiplier.setFill(Color.CHARTREUSE);

}

public void reset() {

    SnakeBody.setX(150);
    SnakeBody.setY(150);

    Food.setX(600);
    Food.setY(600);

    rightSpeed = 0;
    upSpeed = 0;
    leftSpeed = 0;
    downSpeed = 0;
    SnakeSpeed = 4;

    if (canvas.getChildren().contains(SpeedBoost)) {
        canvas.getChildren().remove(SpeedBoost);
    }

    if (canvas.getChildren().contains(ScoreMultiplier)) {
        canvas.getChildren().remove(ScoreMultiplier);
    }

    score = 0;
    Score.setText("Score: " + score);

    Snakes.clear();

    Objects();
    ;

}

private class Timer extends AnimationTimer {

    @Override

    public void handle(long l) {

        // Timer timer2 = new Timer();
        Shape overlap2 = Shape.intersect(SnakeBody, SpeedBoost);

        if (overlap2.getBoundsInLocal().getWidth() > 0 || overlap2.getBoundsInLocal().getHeight() > 0) {

            SpeedBoost.setX(4000); //Moves the object outside of the canvas.
            SpeedBoost.setY(4000);

            Booster = 10;
        }

        Shape overlap3 = Shape.intersect(SnakeBody, ScoreMultiplier);

        if (overlap3.getBoundsInLocal().getWidth() > 0 || overlap3.getBoundsInLocal().getHeight() > 0) {

            ScoreMultiplier.setX(4000); //Moves the object outside of the canvas.
            ScoreMultiplier.setY(4000);

            Multiplier = 10;

        }

        //Snake moving lines
        if (rightSpeed > 0 && facing != RIGHT) {

            facing = RIGHT;

        } else {

            for (int i = Snakes.size() - 1; i > 0; i--) {

                Snakes.get(i).setX(Snakes.get(i - 1).getX());
                Snakes.get(i).setY(Snakes.get(i - 1).getY());

            }

        }

        SnakeBody.setX(SnakeBody.getX() + rightSpeed - leftSpeed);
        SnakeBody.setY(SnakeBody.getY() + downSpeed - upSpeed);

        //Boundaries for the snake
        if (SnakeBody.getX() <= 100 || SnakeBody.getY() <= 100) {

            if (!canvas.getChildren().contains(EndScreen)) {
                canvas.getChildren().addAll(EndScreen, GameOver);

            }

        }

        if (SnakeBody.getX() >= 1170 || SnakeBody.getY() >= 870) {

            if (!canvas.getChildren().contains(EndScreen)) {
                canvas.getChildren().addAll(EndScreen, GameOver);

            }
        }

        Shape overlap = Shape.intersect(SnakeBody, Food);

        if (overlap.getBoundsInLocal().getWidth() > 0 || overlap.getBoundsInLocal().getHeight() > 0) {

            Food.setX(rand.nextInt(1200));
            Food.setY(rand.nextInt(900));

            if (Multiplier == 5) {

                Score2 = Score2 + 1;
                Score.setText("Score: " + Score2);

            } else {

                score = score + 1;
                Score.setText("Score: " + score);

            }

            if (score > 5) {

                if (!canvas.getChildren().contains(SpeedBoost)) {

                    SpeedBoost.setX(350);
                    SpeedBoost.setY(350);

                    canvas.getChildren().add(SpeedBoost);

                }
            }

            if (score >= 4) {

                if (!canvas.getChildren().contains(ScoreMultiplier)) {

                    ScoreMultiplier.setX(100);
                    ScoreMultiplier.setY(100);

                    canvas.getChildren().add(ScoreMultiplier);
                }
            }

            if (leftSpeed > 0) {

                for (int i = 0; i < 5; i++) { //Adds 5x the rectangles, preventing the slow growing.

                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);
                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);

                }
            }

            if (rightSpeed > 0) {

                for (int i = 0; i < 5; i++) {

                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);
                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);

                    canvas.getChildren().addAll(r);
                }

            }

            if (upSpeed > 0) {

                for (int i = 0; i < 5; i++) {
                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);

                    Snakes.add(r);
                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);
                }

            }

            if (downSpeed > 0) {

                for (int i = 0; i < 5; i++) {
                    Rectangle r = new Rectangle(Snakes.get(Snakes.size() - 1).getX(), Snakes.get(Snakes.size() - 1).getY(), 30, 30);

                    Snakes.add(r);

                    r.setFill(Color.GOLD);
                    r.setStroke(Color.WHITE);
                    canvas.getChildren().addAll(r);
                }
            }

        }

        if (Food.getX() <= 100) {
            Food.setX(rand.nextInt(1200));

        }

        if (Food.getY() <= 100) {
            Food.setY(rand.nextInt(900));

        }

        if (Food.getX() >= 1170) {
            Food.setX(rand.nextInt(1200));

        }

        if (Food.getY() >= 870) {
            Food.setY(rand.nextInt(900));

        }

    }

}

public void start(Stage primaryStage) {

    canvas = new Pane();
    scene = new Scene(canvas, 1300, 1300, Color.BLACK);
    Objects();

    /*Shape overlap5 = Shape.intersect(SnakeBody, Food);

    if (overlap5.getBoundsInLocal().getWidth() > 0 || overlap5.getBoundsInLocal().getHeight() > 0) {

        timeCount = timeCount - 1;
        Time = new Text(700, 60, "Time Survived: " + timeCount);
        Time.setFont(font1);
        Time.setFill(Color.YELLOW);

    }*/
    EndScreen = new Rectangle(1300, 1300);
    EndScreen.setFill(Color.BLACK);

    poly1 = new Polygon(points1);
    poly1.setFill(Color.DARKBLUE);
    poly1.setStroke(Color.GREY);
    poly1.setStrokeWidth(3);

    font1 = Font.font("Arial", 24);
    font2 = Font.font("Arial", 48);

    GameOver = new Text(500, 500, "Game Over");
    GameOver.setFont(font2);
    GameOver.setFill(Color.RED);

    //Reset = new Text(650, 650, "You survived for: " + timeCount);
    Score = new Text(250, 60, "Score: " + score);
    Score.setFont(font1);
    Score.setFill(Color.YELLOW);

    HighScore = new Text(700, 60, "High Score: ");
    HighScore.setFont(font1);
    HighScore.setFill(Color.YELLOW);

    canvas.getChildren().addAll(poly1, Score, Food);
    Snakes = makeSnakeBodies();
    canvas.getChildren().addAll(Snakes);

    scene.setOnKeyPressed(new EventHandler() {

        public void handle(KeyEvent evt) {

            if (Multiplier == 10) {

                Score2 = score * 2; //Multiplies score

                Multiplier = 5; //Any value other than 10

            }

            if (Booster == 10) {

                if (evt.getCode().equals(KeyCode.Q)) {

                    SnakeSpeed = 15;

                }

                if (evt.getCode().equals(KeyCode.A)) {

                    SnakeSpeed = 4;

                }
            }

            if (evt.getCode().equals(KeyCode.ENTER)) {


                reset();

                //AnimationTimer class1 = new Timer(); // Code resets the Objects() method but not the animation timer class
            }

            if (evt.getCode().equals(KeyCode.RIGHT) && leftSpeed == 0) {

                rightSpeed = SnakeSpeed;
                upSpeed = 0;
                leftSpeed = 0;
                downSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.UP) && downSpeed == 0) {

                upSpeed = SnakeSpeed;
                rightSpeed = 0;
                leftSpeed = 0;
                downSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.DOWN) && upSpeed == 0) {

                downSpeed = SnakeSpeed;
                rightSpeed = 0;
                leftSpeed = 0;
                upSpeed = 0;

            } else if (evt.getCode().equals(KeyCode.LEFT) && rightSpeed == 0) {

                leftSpeed = SnakeSpeed;
                rightSpeed = 0;
                upSpeed = 0;
                downSpeed = 0;

            }

        }

    });

    primaryStage.setTitle("Snake");
    primaryStage.setScene(scene);
    primaryStage.show();
    Timer timer = new Timer();
    timer.start();

}

public ArrayList makeSnakeBodies() {

    ArrayList joints = new ArrayList<>();

    int x = 150;
    int y = 150;

    SnakeBody = new Rectangle(x, y, 30, 30);
    SnakeBody.setFill(Color.GOLD);
    SnakeBody.setStroke(Color.WHITE);
    joints.add(SnakeBody);

    return joints;

}

}

If you need certain sections of code, I can publish them separately. Thanks again!